OOP's Constructor

 The constructor is also a method.

No return/keywords such as void, int, float etc, are not used before method name.

Constructor name also created using class name.

No calling required. Constructoer is automatically called while creating an object.


Example 01 - file saveAs cons.java

compail command -

javac cons.java   ↪

java cons    ↪

class cons{
    public static void main(String[] args){
        cons obj = new cons();
    }
    cons(){
        System.out.println('Hello world');
    }
}


Example 02 - file saveAs squar.java

compail command -

javac squar.java   ↪

java square     

class squar{
    public static void main(String[] args){
        squar obj1 = new squar(20);
    }
    squar(int a){
        System.out.println("Area = " + a*a);
    }
}




Comments

Popular posts from this blog