A
constructor is a special method that is used to initialize a newly
created object and is called just after the memory is allocated for
the object.
Rules for creating a Java Constructor
It
has the same
name as
the class
It
should not return a value not even void
Example:
class Demo{
int value1;
int value2;
Demo(){
value1=10;
value2=20;
System.ou.println("inside constructor");
}
public void display(){
System.out.prinln("value1=" +value);
System.out.prinln("value1=" +value);
}
public void main(String args[]){
Demo d = new Demo();
d.display();
}
}
Output:
Inside Constructor value1 = 10 value2 = 20
0 Comments