Constructor Vs Method in Java Programming Language

Generally Constructor and Methods in java are looks similar. But there are lots of differences between these two concepts in java. Let us discuss one by one and try to understand difference between these two.

Definition:

Constructor is a block with class name used to initialize instant variable during object creation.

Important point on constructor

  • A constructor is a block of code similar to a method that’s called when an instance of an object is created.
  • A constructor doesn’t have a return type.
  • The name of the constructor must be the same as the name of the class.
  • Unlike methods, constructors are not considered members of a class.
  • Two types of constructor,
    • Default constructor (no-arg constructor)
    • Parameterized constructor.
  • If there is no constructor in a class, compiler automatically creates a default constructor.
  • Default constructor is used to provide the default values to the object like 0, null etc. depending on the type.

Example

public class SampleClass{	
	//Parameterized constructor
	//Constructor name same as Class name i.e. SampleClass
	SampleClass(int x){
		System.out.println("Child class with parameter");		
	}
	
	//Default constructor
	SampleClass(){
		System.out.println("Child class without parameter");	
	}
	
	//Method	
	public void Display(){
		System.out.println("Inside method");	
	}

	public static void main(String[] args) {	
		SampleClass obj1 = new SampleClass();	// Calls Default Constructor (No argument constructor)
		SampleClass obj2 = new SampleClass(10);	// Calls Parameterized constructor
		obj1.Display();		//Method call
	}
}

Output:
Child class without parameter
Child class with parameter
Inside method

Difference between Constructor and Method

Java Constructor Java Method
Constructor is used to initialize the state of an object. Method is used to expose behavior of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if you don’t have any constructor. Method is not provided by compiler in any case.
Constructor name must be same as the class name. Method name may or may not be same as class name.

2 thoughts on “Constructor Vs Method in Java Programming Language”

  1. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and all. However imagine if you added some great graphics or video clips to give your posts more, “pop”! Your content is excellent but with images and video clips, this website could certainly be one of the greatest in its field. Amazing blog!

Leave a Comment

Your e-mail address will not be published.