OCA Java SE 8 Building Blocks - Creating Objects








Constructors

To create an instance of a class, write new before it. For example:

Random r = new Random();

First, declare the type Random and give the variable a name r.

r stores a reference to the object.

Then you write new Random() to actually create the object.

Random() looks like a method and is called constructor, which is a special type of method that creates a new object.

Now it's time to define a constructor:

public class Main { 
  public Main() { 
    System.out.println("in constructor"); 
  } 
} 

The name of the constructor matches the name of the class, and there's no return type.

You'll likely see a method like this on the exam:

public void Main() { } // NOT A CONSTRUCTOR 

The purpose of a constructor is to initialize fields.

Another way to initialize fields is to do so directly on the line on which they're declared.

This example shows both approaches:

public class Rectangle { 
  int num = 0;// initialize on line 
  String name; 
  public Rectangle() { 
    name = "r";// initialize in constructor 
  } 
} 

The compiler can create a "do nothing" default constructor for you.





Object Fields

It's possible to read and write instance variables directly from the caller.

public class Main{
  public static void main(String[] args) { 
    Rectangle rect = new Rectangle(); 
    rect.length = 1;    // set variable 
    System.out.println(rect.length);  // read variable 
  } 
}

class Rectangle { 
  int length;// instance variable 

} 

The class gets length directly to print it out.

This class sets length to 1.

You can even read and write fields directly on the line declaring them:

public class Main{
  public static void main(String[] args) { 
    Rectangle rect = new Rectangle(); 
    rect.length = 1;    // set variable 
    System.out.println(rect.length);  // read variable 
  } /*ww w.  j  av a2 s  .  com*/
}

class Rectangle { 
  int length = 10;// instance variable 

}

The code above generates the following result.





Instance Initializer Blocks

The code between the braces {} is called a code block.

Anywhere you see braces is a code block.

Code blocks can appear inside a method.

Code blocks can appear outside a method, which are called instance initializers.

public class Main{
   { System.out.println("Snowy"); } //instance initializers

   public static void main(String[] args) { 
     { System.out.println("Feathers"); } 
   } 
}

There are three code blocks and one instance initializer in the code above.

To count code blocks, just count the number of pairs of braces.

If there aren't the same number of open { and close } braces, the code doesn't compile.

Order of Initialization

Fields and instance initializer blocks are run in the order in which they appear in the Java source file.

The constructor runs after all fields and instance initializer blocks.

Let's look at an example:

public class Main { 
   private String name = "A"; 
   { 
      System.out.println("setting field"); 
   } 
   public Main() { 
      name = "B"; 
      System.out.println("setting constructor"); 
   }
   public static void main(String[] args) { 
      Main chick = new Main(); 
      System.out.println(chick.name); 
   } 
} 

We start with the main() method because that's where Java starts execution.

First it initializes name to "A". Next it executes the print statement in the instance initializer.

Once all the fields and instance initializers have run, Java returns to the constructor and changes the value of name to "B" and then prints another statement.

At this point, the constructor is done executing.

Order is important for the fields and blocks of code.

You can't refer to a variable before it has been initialized:

{ System.out.println(name); }  // DOES NOT COMPILE 
private String name = "A"; 

Question

What do you think this code prints out?

public class Main { 
  public Main() { 
    number = 5; /*from w w w  .  j  a va2s  . c om*/
  } 
  public static void main(String[] args) { 
    Main m = new Main(); 
    System.out.println(m.number); 
  } 
  private int number = 3; 
  { number = 4; } 
} 

Fields and blocks are run first in order, setting number to 3 and then 4.

Then the constructor runs, setting number to 5.

The code above generates the following result.

Ordering Elements in a Class

Comments can go anywhere in the code.

The following table lists the elements of a class.

ElementRequired?Where does it go?
Package declarationNoFirst line in the file
Import statementsNoImmediately after the package
Class declarationYesImmediately after the import
Field declarationsNoAnywhere inside a class
Method declarationsNoAnywhere inside a class

The following code shows the correct order of elements in a Java source file.

package structure;   // package must be first non-comment 

import java.util.*;  // import must come after package 

public class Main { // then comes the class 
  double weight;       // fields and methods can go in either order 
  double height;       // another field
  public double getWeight() { 
    return weight; 
  } 
}