Constructors in JAVA

Hello guys, we learnt how to create an object, we also learnt few steps to create an object, but there is little add on in order to create a complete object.

So the steps are:

  1. Create an address variable.
  2. Use new operator to allocate the memory for an object.
  3. Execute the Constructor to initialize instance/object variable.
  4. The address returned by the new operator must be collected by the address variable.

So these are the final steps to create a complete object, and this new point constructor we will discuss here. Below is the example which we saw in the previous post, but this one is with changes.

class Dog { 
     String name; 
     int cost; 
     String color; 

     // Default constructor
     Dog() {    
          name=null; 
          cost=0; 
          color=null; 
     }
     //parametrized constructor
     Dog(String name, int cost, String color) { 
          this.name=name; 
          this.cost =cost; 
          this.color=color; 
     }
     void display(){
     System.out.print("Name : " name +" "+"Cost : "+ cost +" "+"Color :"+ color);  
}
class DogMain{ 
     public static void main(String[] args) { 
          Dog d = new Dog(); 
          Dog d1 = new Dog("Scooby",5000,"Black"); // we need to give argument according to constructor
         
           d.disp();
           System.out.println();
           d1.disp(); 
     }
}

Constructors

A constructor is a method executed during the construction of an object.

The properties of the constructor include that the name of the constructor is same as the class name and does not contain return type.

On compilation of JAVA program, if there is no constructor, then the compiler will insert a default constructor automatically.

The constructor can not be executed after the creation of an object.

Methods can be executed after the creation of the object.

 

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: