I am learning Java programming, but I am quit confused about constructor and method. What is the use and basic difference between both of them?
I am learning Java programming, but I am quit confused about constructor and method. What is the use and basic difference between both of them?
Constructor:
A constructor is a member function of a class which is used to create objects of that particular class. Constructor has same name as the class.Constructor don't has any return type, and it is invoked by using new operator.
Method:
A method is an ordinary member function of that class in which it is defined. It has its own name, a return type (which may be void), and is invoked using the dot operator.
e.g.
class PQR{
PQR(){ // PQR is a constructor
------
}
PQR( String x){ //PQR Constructor has one argument
-------
}
}
A method has its own name and return type. It is invoked using the dot operator.
Below are the few differences between methods and constructors:
1. A member function of a class is called as constructor.It is used while creating objects of that class. constructor has the same name as the class , with no return type, and It is called using the new operator.
2. Ordinary member function of a class is called method. It has a return type (this can be may be void).
3. In OOPs, a constructor in a class is a special block of statements invoked at the same time of an object is created, otherwise when it is declared .
4. Object responds and receives to a particular type of message through methods. In C++ language a method is of member function
Constructor is a member function of the class,and the name of constructor & name of class is same.
see the below example constructor:
class student{
student(){ //name of Constructor
------
}
student( int a){ //Constructor with integer type of argument
-------
}
}
On the other hands a method is an ordinary member function of a class.
here is both a constructor and a method
class dog{
public dog{} //constructor makes an object of the class dog
public void setFeatures{
string face;
string color;
int legs;
} // this is a method-- basically it adds items to the object
Bookmarks