Home Java Introduction Decisions Loops Classes Access Inheritance Inner Classes Arrays Exceptions Strings Generics Container Input/Output MultiThreading jdk8 Versions Books

Classes


Contents



We study classes in a little bit more depth in this section.

Constructors

We would like a method in a class that we can call and pass arguments to initialize the object at construction. We could create a speical method say "initialize" in the class and call that after the object is created to initialize it. However what if we forget to call the method. Java provides a special method that has the same name and access level as the class. It can take arguments also and the method can be overloaded.

File: Constructor1.java
import java.util.* ;


class Employee1
{
   int id;
}

class Employee2
{
   int id;
   public Employee2()
    {
        System.out.println( "Employee2: Default Constructor" ) ;
    }

}

class Employee3
{
   int id;
   //public Employee3()
    //No default Employee3() constructed
    //by Java
   public Employee3(int idP)
    {
        id = idP ;
        //same as
        this.id = idP ;
        System.out.println( "Employee3: Default Constructor" ) ;
    }

}

class Employee4
{
   int id;
   public Employee4()
    {
        //Calling another constructor
        //must be the first call in the function
        this(1) ;
        System.out.println( "Employee4(): Default Constructor" ) ;
    }

   public Employee4(int idP)
    {
        id = idP ;
        System.out.println( "Employee4():Employee4(int idP) Constructor" ) ;
    }

}


public class Constructor1
{


   public static void main( String args[] )
   {
       //Class does not have a constructor so java
       //creates a default no arg constructor that
       //does nothing.
        Employee1 employee1Object = new Employee1() ;

       //We create a default constructor and call it
        Employee2 employee2Object = new Employee2() ;

        //Can't do. //Java states that you have a constructor
        //that takes an argument . Why don't you use that.
        //Employee3 employee3Object = new Employee3() ;
        Employee3 employee3Object = new Employee3(1) ;

        //An example of one constructor calling another
        Employee4 employee4Object = new Employee4() ;

   } //public static void main( String args[] )


}
C:\WebSite\Learn\2\Java\classes>java Constructor1
Employee2: Default Constructor
Employee3: Default Constructor
Employee4():Employee4(int idP) Constructor
Employee4(): Default Constructor
A constructor gets called anytime we use "new" on the object. If we don't have any constructors then the system will create a default one for us that does not take any arguments and whose body is empty.
If we do not have a default( also called no arg ) constructor defined but have a constructor with arguments then the system will not create a default constructor for us. The class "Employee3" will not let us use "new" with a default constructor.
A constructor method does not return anything. It's only function is to initialize the object. We can have overloaded constructors as "Employee4" shows. A class can have a keyword called "this". This ( no pun intended ) keyword contains a reference to the object that is using the method. It is useful for construction of complex algorithms and also in other cases such as in the "Employee4" class where it's used to call another constructor. If a constructor does call another constructor then the call must be the first statement in the constructor function.

Overloaded Methods



File: Overloaded1.java
import java.util.* ;


class Employee
{
   int id;
   public Employee()
    {
    }

   public void  method1( float x1P )
     {
       System.out.println( "Overloaded 1.") ;
     }


   public void  method1( char ch1P , int x1P )
     {
       System.out.println( "Overloaded 2.") ;
     }
   //valid
   public void  method1( int x1P , char ch1P   )
     {
       System.out.println( "Overloaded 4.") ;
     }

   //Overloaded method must differ in arguments and not
   //just return type.
   /*
   public int  method1( int x1P , char ch1P   )
     {
       System.out.println( "Overloaded 5.") ;
     }
    */



}

public class Overloaded1
{


   public static void main( String args[] )
   {
        Employee employeeObject = new Employee() ;
        employeeObject.method1( 'A' , 21 ) ;
         //Invalid
        //employeeObject.method1( 65 , 21 ) ;
        //ok int gets promoted to float
        employeeObject.method1( 24 ) ;

        //narrowing is invalid
        //double cannot be narrowed to float
        //incompatible types: possible lossy conversion from double to float
        //employeeObject.method1( 24.6 ) ;
   } //public static void main( String args[] )


}

Initialization



File: Initialization.java
import java.util.* ;

class A
{
    A(int i1)
     {
         System.out.println( "A(): " + i1 ) ;
     }
}

class B
{
   //Gets initialized after static
   A normalAObject = new A(1 ) ;
   //Static Gets initialized first. Either through
   //use of A or access the static object
   static A staticAObject = new A( 2 ) ;
   B()
    {
        //Gets initialized after data members initialization
        System.out.println( "B()" ) ;
    }
}

class Employee
{
   int id;
   //class variables get initialized with
   //default values
  boolean b1;
  char c1;
  byte byte1;
  short short1;
  int int1;
  long long1;
  float float1;
  double double1;
  Employee  employeeObject ;

  //Allowed to initizlize
  int int2 = 42 ;

  //Initialization is from top to bottom
  // int j1 = method2(i1); // Illegal forward reference
  int i1 = method1();
  int method1() {
      System.out.println( "method1() getting called." ) ;
      return 10 ; }
  int method2(int x1) { return x1 * 2; }

  void printInitialValues()
  {
    System.out.println( "Data type      Initial value");
    System.out.println( "boolean        " + b1 );
    System.out.println( "char           [" + c1 + "]" );
    System.out.println( "byte           " + byte1 );
    System.out.println( "short          " + short1 );
    System.out.println( "int            " + int1 );
    System.out.println( "long           " + long1 );
    System.out.println( "float          " + float1 );
    System.out.println( "double         " + double1 );
    System.out.println("reference      " + employeeObject );
  }
   public Employee()
    { //Initialization can be done here
      //The initialization at the class data members will
      //be done firts.
      System.out.println( "Employee() constructor." ) ;
    }

   public void  method1( float x1P )
     {
       //method data members
       int i1 ;

       //Invalid. Won't let us use i1 unless it is initialized
       //System.out.println( i1 ) ;
     }
  //data members can be spread through out the class
  //and can come after the methods but will be initialized
  //before the methods.
  int i2 = method1();



}

public class Initialization
{


   public static void main( String args[] )
   {
        Employee employeeObject = new Employee() ;
        employeeObject.printInitialValues() ;
        System.out.println( "We have not used A or B. " )  ;
        B BObject1 = new B() ;

   } //public static void main( String args[] )


}
method1() getting called.
method1() getting called.
Employee() constructor.
Data type      Initial value
boolean        false
char           [ ]
byte           0
short          0
int            0
long           0
float          0.0
double         0.0
reference      null
We have not used A or B.
A(): 2
A(): 1
B()
The above shows how we can have static data members along with normal data members and a constructor. Data members in a class are initialized with their default values if no initialization is provided. The static data members only get initialized once and that is when either an instance of the class is created or the static data member is accessed.
Explicit static data initialization

File: Initialization1.java
import java.util.* ;

class A
{
    A(int i1)
     {
         System.out.println( "A(): " + i1 ) ;
     }
}

class B
{
   //Gets initialized after static
   A normalAObject1 ;
   A normalAObject2 ;
   {
      normalAObject1 = new A( 1 ) ;
      normalAObject2 = new A( 2 ) ;
   }
   //Static Gets initialized first. Either through
   //use of A or access the static object
   static A staticAObject1 ;
   static A staticAObject2 ;
   //Block of code executed only once
   static
    {
        staticAObject1 = new A( 3 ) ;
        staticAObject2 = new A( 4 ) ;
    }


   B()
    {
        //Gets initialized after data members initialization
        System.out.println( "B()" ) ;
    }
}


public class Initialization1
{


   public static void main( String args[] )
   {
       //Kicks off static initialization
       //as well as object data initialization
        B BObject1 = new B() ;
        System.out.println( "Another instance of B created." ) ;
        B BObject2 = new B() ;
   } //public static void main( String args[] )


}

Exercises:
1)

File: ex1.java














1)
File: soln1.java
2)