Login    New User    Forgot Password    Help      

Calling Constructors

Java Tutorials

A java Constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.

Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.

Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.

The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.

Example

// Multilevel hierarchy
// Calling constructors
// When a class hierarchy is created in what order are the             // constructors for
// The classes that make up the hierarchy called
 
class base
{
int a;
             
        base()
        {
        a=10;
        System.out.println("Base class");
        System.out.println("Value of b is "+a);
        }

}

class drive extends base
{
int b;

     drive()
     {
     b=20;

     System.out.println("\ndrive class");
     System.out.println("Value of a is "+super.a);
     System.out.println("Value of b is "+b);
     }

}

class drive1 extends drive
{
int c;

     drive1()
     {
     c=30;

     System.out.println("\nDrive one class");
     System.out.println("Value of a is "+super.a);
     System.out.println("Value of b is "+super.b);
     System.out.println("Value of c is "+c);
     }

}

class herit5
{
public static void main(String args[])
{

drive1 ob1=new drive1();

}
}

Output

Java Tutorials