Ask a Teacher



DIFFERENTIATE BETWEEN METHODS & CONSTRUCTORS.

A constructor is technically a type of method, but it is a very special type. Whereas other methods can be used to do just about anything, the only purpose of a constructor method is to create an instance of the class that contains it, often with parameters passed to it through another part of the program. This instance is called an "object" and is a central part of not only Java, but other object-oriented languages as well. A constructor method always has the same name as its containing class, and does not have a return type.
Think of it this way: a class in Java is like a generic blueprint for a house. Your instance variables are like different attributes of the house - how many bathrooms will your house have, what colour will it be? Once you decide on the exact specifications for your house, you can give those parameters to the construction company, which will actually create that house. That's what a constructor method does - takes input parameters (or, lacking them, sets defaults) and creates an object.


First difference between method vs constructor in Java is that name of constructor must be same with name of the Class but there is no such requirement for method in Java. methods can have any arbitrary name in Java.

Second difference between method and constructor in Java is that constructor doesn't have any return type but method has return type and return something unless its void.

Third difference between constructor and method in Java is that Constructors are chained and they are called in a particular order, there is no such facility for methods.

Unlike method, constructor, yet declared in class doesn't considered as member of Class. Constructors are not inherited by child classes but methods are inherited by child classes until they are made private. on which case they are only visible in class on which they are declared. 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.

Another difference between method and constructor in Java is that special keyword this and super is used to call constructor explicitly. no such thing for method, they have there own name which can be used to call them.


comments powered by Disqus