Java Constructor
In Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automatically when we use the "new" keyword to create an object.
Key points:
*The name of the constructor must be the same as the class name.
*It does not have a return type (not even void).
*It is mainly used to initialize values when an object is created.
Syntax of Constructor:
class ClassName {
// Constructor
ClassName() {
// initialization code
}
}
sample program
class Student {
int RollNo;
String name;
int age;
String course;
int mark;
Student(int RollNo, String name, int age, String course, int mark) {
this.RollNo =RollNo;
this.name = name;
this.age = age;
this.course = course;
this.mark = mark;
}
void display() {
System.out.println("RollNO:" + RollNo + " " +"Name:"+ name + " " +"age:" + age + " " + "course:" + course + " " + "Mark:" + mark);
}
}
public class Constructor {
public static void main(String[] args) {
Student s1 = new Student(16, "Surya", 26, "Java", 95);
s1.display();
}
}
Output:
RollNO:16 Name:Surya Age:26 Course:Java Mark:95
Top comments (0)