Java Constructors
Java Constructors
A constructor is a special method used to initialize objects. It has the same name as the class and
1. Default Constructor
Syntax:
class ClassName {
ClassName() {
Example:
class Car {
Car() {
System.out.println("Car is created");
Output:
Car is created
Explanation:
2. Parameterized Constructor
Syntax:
class ClassName {
Example:
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
void display() {
s1.display();
Output:
Explanation:
- Constructor Student(String n, int a) is used to set values while creating object s1.
Important Points: