Core Java - SPLessons

Java Constructor

Chapter 13

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Java Constructor

Java Constructor

shape Description

Java Constructor is a block just like a method used for object initialization. It is a special method invoked by new operator at the time of instance creation. Java Constructor will have default constructor as well as parameterized constructor. Following is the syntax to declare the constructor.

constructorName(args)
{
------------
-----------
return;
}

Default Constructor

shape Description

If the developer can not mention parameters in constructor then it becomes default constructor. Following is the syntax for the default constructor.

class splessons
{
splessons()//where splessons is the constructor.
}

shape Example

defaultconstructor.java

public class defaultconstructor {
	defaultconstructor()
	{
		System.out.println("Hello welcome to SPlessons.");
	}
	public static void main(String args[])
	{
		defaultconstructor d=new defaultconstructor();
		
	}
}

Output:
When compile the code following is the output will be generated.

Hello welcome to SPlessons.

Parameterized Constructor

shape Description

If developer pass any arguments through the constructor then it becomes Parameterized Constructor. Following is an example.

shape Example

Following is an example where arguments are passing through the constructor.
Splesson.java


public class Splesson {
	int id;  
    String name;  
      
    Splesson(int i,String n){  
    id = i;  
    name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    	Splesson s1 = new Splesson(100,"sam");  
    	Splesson s2 = new Splesson(111,"Aryan");  
    s1.display();  
    s2.display();  
   }  
}

Output:
When compile the code following is the output will be generated.

100 sam
111 Aryan

Constructor Overloading

shape Description

  • Developing more than one constructor in java class with different argument list is known as Constructor Overloading.
  • To achieve constructor overloading the arguments should differ in any one of the following.
  • If one tries to develop with the same argument list then compiler throws error.
  • Whenever the object member is to be initialized with different arguments, then go for developing overloading constructor.


shape Example

package com.spl.co;

public class ConstructorOverloading {
	public static void main(String[] args) {
		System.out.println("Program starts");
		Demo dRef1=new Demo(5);
		System.out.println("k value:"+dRef1.k);

		Demo dRef2=new Demo(5.2);
		System.out.println("d value:"+dRef2.d);

		Demo dRef=new Demo(5,5.2);
		System.out.println("k value:"+dRef.k);
		System.out.println("d value:"+dRef.d);

		System.out.println("Program ends");

	}
}
class Demo
{
	int k;
	double d;
	//overloaded constructor
	Demo(int a)
	{
		System.out.println("Running Demo(int) constructor");
		k=a;
	}
	Demo(double b)
	{
		System.out.println("Running Demo(double) constructor");
		d=b;
	}
	Demo(int a,double b)
	{
		System.out.println("Running Demo(int,double) constructor");
		k=a;
		d=b;
	}
}

Constructor overloading is a strategy in Java in which a class can have any number of constructors that vary in parameter lists.The compiler separates these constructors by considering the quantity of parameters in the rundown and their sort.
Output:

Program starts
Running Demo(int) constructor
k value:5
Running Demo(double) constructor
d value:5.2
Running Demo(int,double) constructor
k value:5
d value:5.2
Program ends

“This” keyword

shape Description

  • Java provides a special keyword to store the address of current object is caled “This”. “This” keyword should be used only inside constructor body or non static context.
  • To differentiate local variable and object members “this” keyword can be used for referring object members.


shape Example

The following is an example without using this keyword.

package com.splessons;

class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
rollno=rollno;  
name=name;  
fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
  
class Splesson{  
public static void main(String args[]){  
Student s1=new Student(100,"john smith",6000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

Where instance variables and formal parameters are same, to show the variation between them this keyword will be used.
Output:

0 null 0.0
0 null 0.0

The solution for the above code by using This keyword.

package com.splessons;

class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
this.rollno=rollno;  
this.name=name;  
this.fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
  
class Splesson{  
public static void main(String args[]){  
Student s1=new Student(100,"john smith",6000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

In any case formal parameters and instance parameters are different then no need to use This keyword.
Output:

100 john smith 6000.0
112 sumit 6000.0

“This” statement

shape Description

  • A constructor of the class can invoke another constructor of the same class using “this” statements.
  • “this” statement must be the first statement inside the constructor .
  • In a constructor body, two “this” statements cannot be used.
  • “this” statement should be used only inside the constructor.

shape Example

package com.spl.statement;

public class ThisStatement {
	public static void main(String[] args) {
		System.out.println("Program starts");
		Demo dRef=new Demo(5.2);
		System.out.println("Program ends");

	}
}

class Demo
{
	Demo()
	{
		System.out.println("Running Demo() constructor");
	}
	Demo(int a)
	{
		//this statement(calling Demo() constructor)
		this();
		System.out.println("Running Demo(int) constructor");

	}
	Demo(double d)
	{
		//calling Demo(int) constructor
                this(5);
		System.out.println("Running Demo(double) constructor");

	}
}

Output:

Program starts
Running Demo() constructor
Running Demo(int) constructor
Running Demo(double) constructor
Program ends

Summary

shape Key Points

  • This keyword will take only same values
  • The constructor name and class name should be same.