Java Constructors

 Constructor in Java

In java a constructor is called a special method. It is used to create objects in java. A constructor is called whenever we initialize an object. It has some special features:

  • It has same name as that of a class.
  • It does not have any return type.
  • It's syntax is similar to method.
  • A java constructor cannot be static, final or abstract.
  • A class always have a default constructor whether you have declared it or not. But if you define a custom constructor then default constructor is no longer in use.
There are two types of constructors in Java:
  • No-Parameterized Constructor (Default Constructor)
  • Parameterized Constructor
No-Parameterised Constructor
As the name suggests, this constructor doesn't have any parameter in it's signature.

Syntax for Default Constructor:

public class MyClass{  
	
	// Creating a default constructor  
	MyClass(){
		System.out.println("Object created");
	}  

	// Main method  
	public static void main(String args[]){  
		//Calling a default constructor  or Creating an object of MyClass
		MyClass obj = new MyClass();  
	}  
}  

Explanation of example code:

  • We have created a default constructor "My Class", which will print "Object created" whenever we create an object.
  • In main method, we are calling the constructor to initialize our object named "obj".
Output:
Object Created

Parameterized Constructor:
It's a constructor which accepts parameters. It can have one or more parameters. It is used to provide different values to different objects.

Syntax for Parameterized Constructor:

public class MyClass {

  // Declare variable
  int num;

  // Parameterized Constructor
  public MyClass(int y) {
    num = y;
  }

  public static void main(String[] args) {
    // Call the parameterized constructor and pass parameter 5
    MyClass myObj = new MyClass(5);
    // Print num
    System.out.println(myObj.num);
  } 
}

Explanation of the example code:
  • We declared a variable num.
  • Declared a parameterized constructor with parameter int y.
  • Inside constructor we are initialising num's value to y.
  • In main method, we are calling parameterized constructor and passing value 5 to y. It will initialize num to 5 inside the parameterized constructor.
  • Now the value of the num is set to 5 and it'll print 5.
Output:
5



Follow Us

Quora Space | Facebook Page | Telegram Channel
Feel free to ask queries or share your thoughts in comments or email us.

Comments

Popular posts from this blog

10 Best Demo Websites for Automation Testing Practice

Automate E-Commerce Website using Selenium Webdriver

Automate Browser Actions on Godaddy.com using Selenium

Automate Amazon Website 'Menu links' using Selenium