You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A constructor is a special method which is automatically called by jvm whenever object is created
Constructor name is same as class name and it should not return any value
It cannot be static
constructor may or may not be private
Types of constructor
Default Constructor
Parametrized Constructor
Default constructor
There are 2 types of default constructor:
System-defined default constructor
Whenever we are not creating any constructor in the class, then system will define a constructor called: System-defined defined constructor
User-defined default constructor
A constructor without any parameter is called User-defined default constructor
/*Without constructor:System-defined def cons*/classSample{
inta, b;
voidaccept(){
a = 100;
b = 200;
}
voiddisplay(){
System.out.println("Value of a: " + a + " Value of b: " + b);
}
}
classDemo{
publicstaticvoidmain(Stringargs[]){
Sampleobj = newSampleobj.accept()
obj.display() // Value of a: 100 Value of b: 200
}
}
/*With constructor:User-defined def cons*/classSample{
inta, b;
Sample(){
a = 100;
b = 200;
}
voiddisplay(){
System.out.println("Value of a: " + a + " Value of b: " + b);
}
}
classDemo{
publicstaticvoidmain(Stringargs[]){
Sampleobj = newSampleobj.accept()
obj.display() // Value of a: 100 Value of b: 200
}
}