Java Constructors

         Constructor is a block of codes similar to the method. It is called when an instance of the class is created.

 constructor must declare name same as class name , constructor hasn't return type


ex -:



when you creating object from java class, the constructor in that class runs automatically.

ex-:

-------------------------------------Box.java-------------------------------------------------------------




-------------------------------Demo.java-------------------------------------------------------------------------

Output -:


Case 1-:

Constructor can't run as another methods. it automatically runs when creating an object

ex -:


//gives compile error


Case 2-:

   we can create a method its name same as class name & has return type.  It is not a constructor. its run same as another method.

ex-:
-----------------------------------------Box.java---------------------------------------------------------------


------------------------------------Demo.java-----------------------------------------------------------------

Output -:


Case 3 -:

        We can create parameterized constructor. 
ex-:

class Box{=

Box(int a, int b){
System.out.println("This is a method");
}
}

Case 4-:

suppose, you didn't create a constructor in a class. its no matter. compiler automatically create a default constructor when creating new object


Case 5-: Constructor overloading

In the same class, having more than one constructor with same name but different argument list.
(Similar to method overloading)

Case 6-:

when you use "this()" keyword inside a constructor, It executes default constructor.
"this()" keyword must be a first line in the constructor block/ method block.

ex-:
------------------------------------------------------Box.java------------------------------------------------------

-------------------------------------------------Demo.java----------------------------------------------------------



Output -:

Case 7 -:

It is not possible to call back from the same constructor to the same constructor
ex-:

Comments

Popular posts from this blog

Create your first Java program

Java Variables

Java OOP