RastcodeS

Where we take good care of both your front and back-end needs

Great place to take your code to the next level

Checkout my work and get in touch



RastcodeS Logo
Go Back

Java Break - Creating Objects - Java Core Part - IV


Java



Written by Rastko

date - 03/Sep/18 | views - 193

Java Break - Creating Objects - Java Core Part - IV

     Creating new java objects, writing to and reading from object fields. Order of initialization explained.

     This is the fourth chapter in the Java Break series. For the previous parts, check out the links below:

Java Break - Class Structure - Java Core Part - I

Java Break - Main Method - Java Core Part - II

Java Break - Packages and Imports - Java Core Part - III

 

New Objects

 

In the previous chapters, we've already created some objects to illustrate certain Java behavior, but we haven't really explained how it works. That will be the topic of today's article, as using Java without creating new objects, would be kind of pointless.


 

Constructors

 

     As we've previously stated, most java classes are just blueprints for the objects. These objects are the actual gears of our applications. To create a new object, we'll use an example of a Random class:

Random random = new Random();

 

     This seems very simple, but let's dissect the code. First we declare the type we're making, in this case - Random. Next, we name a variable to hold the object reference - random. Note - we are being specific when we say we're storing a reference and not the actual object. Java objects are not accessed directly, but via a reference. Finally, we make a new object by writing new Random(). Now, you might be confused by the parentheses after the Random. It looks like a method, right? Well, it kind of is. It's just a special type of method, called constructor.

     Now that we know how instantiate a class, let's look at how we can make our own constructor:

public class Person {
   public Person() {
      System.out.println("Constructing a Person object");
   }
}

 

     This is really simple. Each time we instantiate a new object, the print line method will be called. But there are some rules. For this to be a constructor:

  • The name has to match the name of the class

  • There is no return type

 

     For example, this is not a constructor:

public void Person() {

}

 

     Why? It has a return type, in this case - void. It would behave like a regular method, even though it wouldn't do anything.

     We mainly use constructors to initialise fields and maybe do some setup work, but really you can put any code inside. Alternatively, you can initialise the fields on the same line you've declared them:

public class Person {

   int age = 30;
   String name;

   public Person() {
      name = "John";
   }
}

 

     As you can see, the age field is being initialised on the same line it is declared on. On the other hand, we have initialised the name field inside the constructor.

     It is not necessary to write a constructor as the compiler will add the no-argument constructor for you automatically. There is an exception to this rule, but we'll discuss that later, when we explore class inheritance.


 

Writing and Reading Fields

 

     The simplest way to write to object fields and read from them, is to do it though the object itself. In this use case, we would call this object the caller:

public class Person {
   
   int age;

   public static void main(String[] args) {
      Person john = new Person();
      john.age = 30;
      System.out.println(john.age);
   }
}

 

     As you can see, we declare a Person class, which has a field age, of type integer. Inside the main method we create a new person object. Next, we set the age value and then get the age, by simply writing john.age for both actions.

     As we've stated before, we can write and read fields on the same line they are declared:

public class Person {
   String firstName = "John ";
   String lastName = "Doe";
   String fullName = firstName + lastName;
}

 

Instance Initializer

 

     When we talked about the main method, we mentioned the method body which is inside the curly braces. Really any code inside these braces is called a code block. When these code blocks appear outside a method, or a control statement, we call them instance initializers:

public static void main(String[] args) {
   {System.out.println("Inside Code Block - Not an Instance Initializer");}
}

{System.out.println("Instance Initializer");}

 

     If you're counting there are three called blocks here including one instance initializer at the bottom.

 

Order of Initialization

 

     You might be wondering, if we have both the instance initializers and a constructor, do they intrude on each other's territory? Well, no. That's because instance initializers are executed before the constructor is. There are other types of initializers and we'll talk about them later. For now, just remember these two rules:

  • Field and instance initializers will be run in the order, in which they appear inside the class

  • The constructor runs after these have finished running

 

     Let's check out an example:

public class Person {
   
   String name = "John";
   {System.out.println("Initializing name field");}
  
   public Person() {
      name = "Bob";
      System.out.println("Setting name in constructor");
   }

   public static void main(String[] args) {
      Person person = new Person();
      System.out.println(person.name);
   }
}

 

     As you see, the instance initializer first sets the name to John. Afterwards, the constructor overrides that, by setting the name to Bob.

     Note - you can't refer to a field that hasn't yet been initialised:

System.out.println(name);
String name = "John";

 

     This wouldn't compile.

     Let's take a look at another, maybe confusing example:

public class Person {
   
   public Person() {
      age= 30;
   }

   public static void main(String[] args) {
      Person person = new Person();
      System.out.println(person.age);
   }

   int age = 40;
   { age = 50; }
}

 

     This code compiles perfectly and the output is 30. It doesn't matter that the initializers are located after the constructor and the main method. They run first, but the constructor has the last say.


 

     In this chapter we have included a lot of theory talk. These confusing examples, you will hopefully never need to write. One reason is, that we're trying to explain, everything you need to know about the building blocks Java. On the other hand, the Java Break series is intended to be a prelude for the - OCA tricky questions series where we'll discuss the hardest questions you may find on the OCA exam.

     To finish off we'll take a look at a real world example:

public class Person {
   
   int age;
   String name;
  
   public Person(int age, String name) {
      this.age = age;
      this.name = name;
   }

   public static void main(String[] args) {
      Person person = new Person(30, "John");
      
      System.out.println(person.age);
      System.out.println(person.name);
   }
}

 

     The class Person declares two fields, age of type integer and name of type String. We don't initialize them after declaration, we let the constructor do that for us. Don't worry about the this keyword, we'll talk about that later. Just note that it is used to access the instance variables. The right hand side are the constructors arguments. When we instantiate a new object, we pass the parameters to the constructor, as we would with any method.

     This is been all for this chapter. On the next Java Break, we'll discuss the differences between the primitive and the reference types. See you then!


View Post/Backend
Login to comment

Comments


No Comments yet. Be the first!

Currently working on a Laravel project

Check it out
Java Break - Declare and Initialize Variables - Java Core Part - VI
Java Break - Declare and Initialize Variables - Java Core Part - VI

     Declaring and initializing variable in Java. How to do it properly and avoid mistakes.

     The sixth chapter...

Java


Recents


Popular