Difference Between Method and Constructor

Advertisements

Prev Tutorial Next Tutorial

Difference Between Method and Constructor in Java

Costructor is the special member funtion of any class and it is call implicitly whenever object of class is created.

  • The name of constructor must be same with the name of the Class but there is no such requirement for a method in Java.
  • Constructor doesn't have any return type but the method has the return type and returns something unless its void. Constructors are chained and they are called in a particular order, there is no such facility for methods.
  • Constructors are not inherited by child classes but methods are inherited by child classes until they are made private. Similarly private constructor means you can not create object of that class from outside, this is one of the technique used to implement Singleton pattern in Java.
  • In Java this and super is used to call a constructor explicitly. no such thing as the method, they have their own name which can be used to call them.

Example Method and Constructor in Java

Example Method and Constructor in Java

public class Customer
{ 
private int account;//data member 
private String name; 
private float amount; 
Customer() //constructor doesn't has return type
{
}
public void deposit(int amount) //method has return type
{
this.amount+=amount; 
} 
}

Difference between Method and Constructor in Java

MethodConstructor
Method can be any user defined nameConstructor must be class name
Method should have return typeIt should not have any return type (even void)
Method should be called explicitly either with object reference or class referenceIt will be called automatically whenever object is created
Method is not provided by compiler in any case.The java compiler provides a default constructor if we do not have any constructor.

Prev Tutorial Next Tutorial

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet


For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements