A
Constructor initializes an object immediately upon creation of an object.
It
has the same name as the class in which it resides and is syntactically similar
to a method.
Constructors
have no return type, not even void.
This is because the implicit return type of class’ constructor is the class
type itself.
Ex:class
Myclass {
int
a;
int b;
Myclass()
{ // default constructor.
a=0;
b=0;
}
Myclass(int
x,int y) { // parameterized constructor.
a=x;
b=y;
}
void Display() {
//Method with no parameters.
System.out.println
(“A= “ +a+ “ B= “+b);
}
}
class
Mymain {
public static void main(String args[]) {
Myclass c1=newMyclass(); //Calling default constructor
Myclassc2=new Myclass(10,20);//Calling
parameterized constructor
c1.Display();
int
sum=c2.sum();
System.out.print("\n
Sum of Second object is:"+sum);
}
}
Output:
A= 0 B= 0
Sum of Second object is: 30
No comments:
Write comments