Java Constructors
Constructors in Java are special methods used to initialize objects. They have the same name as the class and do not have a return type. Constructors are called when an object is created using the new
keyword.
1. Default Constructor
If no constructor is defined, Java provides a default constructor with no parameters.
2. Parameterized Constructor
You can define constructors with parameters to initialize object attributes with specific values.
public class Person {
String name;
int age;
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
3. Creating Objects with Constructors
Person person = new Person("Alice", 30);
System.out.println(person.name); // Outputs: Alice
4. Constructor Overloading
You can have multiple constructors in a class with different parameters.
public class Rectangle {
int width;
int height;
// No-argument constructor
public Rectangle() {
width = 0;
height = 0;
}
// Parameterized constructor
public Rectangle(int w, int h) {
width = w;
height = h;
}
}
5. The this
Keyword
The this
keyword refers to the current object. It's used to differentiate between class attributes and parameters with the same name.
Key Takeaways
- Constructors initialize new objects.
- They have the same name as the class and no return type.
- Parameterized constructors allow setting initial values for attributes.
- Constructor overloading provides flexibility in object creation.
- The
this
keyword helps in referencing the current object's attributes.