Compare method and constructor?
Answers
DIFFERENCES :
▶ The method is used to perform certain tasks .
▶ The constructor is used to initialize the instance variables .
▶ The method name is not the same as class name .
▶ The constructor has the same name as that of the class name .
▶ The method has to be called or invoked .
▶ The constructed is already called by default .
▶ The method has a return type .
▶ The constructor has no return type , not even void .
▶ The method returns a value or returns nothing .
▶ The constructor returns nothing .
Example :-
class parameterized_constructor
{
int a,b;
parameterized_constructor(int x,int y)
{
a=x;
b=y;
}
void display()
{
System.out.println("a="+a);
System.out.println("b="+b);
}
void main()
{
parameterized_constructor p=new parameterized_constructor(10,20);
p.display();
}
}
Here :-
Constructor : parameterized_constructor(int x,int y)
Methods : void display() , void main() .
Method and constructor
First, Comparison between method and constructor.
Method
1) The method has to be invoked
2) The method returns a value
3) Method in java means a block of code
4) The method has a return type .
5) Method is used to perform some normal works
Constructor
1) Constructor is already 'called' by default in Java
2) Constructor returns no program or codes
3) Constructor means less programs
4) Constructor don't have return type
5) Constructor can be used for doing server works
Here is an example:
public void add(int i, int j)
{
int k = i + j;
}
public void add(String s, String t)
{
int k = Integer.parseInt(s) + Integer.parseInt(t);
}
}