Difference Between Method and Constructor
Advertisements
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
Method | Constructor |
---|---|
Method can be any user defined name | Constructor must be class name |
Method should have return type | It should not have any return type (even void) |
Method should be called explicitly either with object reference or class reference | It 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. |
Google Advertisment