Object Oriented Programming - JAVA- Constructor
Object Oriented Programming - JAVA 👽
The constructor is the first thing that runs in a program. Is it true❓ You can answer this at the end of this discussion.
Let's talk about constructor
Constructor...
A constructor is something that holds everything in the program. There are several features in this.
- It is created by the name of the class
- No return type is required
- It's a method
class Sun{
Sun(){
// constructor
}
public static void main (String [] args){
Sun s = new Sun();
}
}
The constructor is executed when the object is called. The object is created in the main method. The object is executed by JVM(Java Virtual Machine). Constructor has two types.
Parameter Less constructor
Here, we have no parameters (arguments) in the argument list.
class Sun{
Sun(){
// constructor
}
public static void main (String [] args){
Sun s = new Sun();
}
}
Parameterized constructor
In parameterized constructors , we have to put arguments to the argument list. This constructor parameter list also act as a parameter list and within the object the parameter list convert to argument list. we can pass the parameter values through the object.
class Sun{
Sun(int x, int y){
// constructor
}
public static void main (String [] args){
Sun s = new Sun(45,23);
}
}
Classes , constructors and object always belong to the object's variable.
Its a nice blog
ReplyDelete