Initializing an Object


The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.

Dog.java (a class example)
// Class declaration 
public class Dog { 
  public static void main( String[ ] args ) {
    Dog tuffy = new Dog( args[0], args[1], Integer.parseInt(args[2]), args[3] );
    System.out.print( tuffy.toString( ) );
  }
  // Instance variables 
  String name; 
  String breed; 
  int    age; 
  String color; 
  // Constructor
  public Dog( String name, String breed, int age, String color ) { 
    this.name  = name; 
    this.breed = breed; 
    this.age   = age; 
    this.color = color; 
  } 
  // Method 1 
  public String getName( )  { return name; } 
  // Method 2 
  public String getBreed( ) { return breed; } 
  // Method 3
  public int getAge( )      { return age; } 
  // Method 4 
  public String getColor( ) { return color; } 
  // Overriding the method toString( )
  @Override
  public String toString( ) { 
    return( this.getName( ) + "|" + this.getBreed( ) + "|" +
            this.getAge( )  + "|" + this.getColor( ) ); 
  } 
}
shell> java Dog        

Output:           Result:

This class contains a single constructor. We can recognize a constructor because its declaration uses the same name as the class and it has no return type. The Java compiler differentiates the constructors based on the number and the type of the arguments. The constructor in the Dog class takes four arguments. The following statement provides “tuffy,” “pointer,” 5, and “white” as values for those arguments:
   Dog tuffy = new Dog( "tuffy", "pointer", 5, "white" );
Note that all classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent’s no-argument constructor (as it contain only one statement; i.e., super();), or the Object class constructor if the class has no other parent (as Object class is parent of all classes either directly or indirectly).




      We get used to that, we endure, we harden,    
      we batten down the hatches (prepare for the trouble)    
      to protect our habits.