What is a constructor in Java?
A constructor has the same name as the class and no return type. It runs automatically when you use new. If you do not write one, Java gives a default constructor with no parameters.
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Riya", 88);
System.out.println(s.name + " " + s.marks);
}
}
Output
Riya 88
Types: default, parameterized and copy constructors. See Java Constructors.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |