Classes and Objects
Classes and Objects in Java
Java is an object-oriented language — almost everything is an object.
Class definition A class is a blueprint. It contains fields (state) and methods (behaviour).
Constructors A constructor initialises a new object. Its name matches the class name and it has no return type. If you don't define one, Java provides a no-argument constructor automatically.
this keyword
Inside instance methods and constructors, this refers to the current object. It is used to:
- Distinguish field names from parameter names.
- Call another constructor in the same class:
this(arg).
new keyword
Allocates memory for a new object and calls its constructor:
Dog d = new Dog("Rex");Key points:
- Fields should generally be
privateto enforce encapsulation. - Provide public getters and setters to control access.
- Multiple constructors with different parameters are allowed (constructor overloading).
Code Examples
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
public void birthday() {
age++;
}
@Override
public String toString() {
return name + " (age " + age + ")";
}
public static void main(String[] args) {
Person p = new Person("Alice", 30);
System.out.println(p);
p.birthday();
System.out.println(p.getName() + " is now " + p.getAge());
}
}Private fields with public getters/setters enforce encapsulation. toString() provides a readable string representation.
public class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
// Delegates to the two-argument constructor
public Rectangle(double side) {
this(side, side);
}
public double area() { return width * height; }
public double perimeter() { return 2 * (width + height); }
public static void main(String[] args) {
Rectangle r = new Rectangle(4, 6);
System.out.println("Area: " + r.area());
Rectangle sq = new Rectangle(5);
System.out.println("Square area: " + sq.area());
}
}this() calls another constructor in the same class, avoiding code duplication. It must be the first statement.
Quick Quiz
1. What does the `new` keyword do?
2. What is the purpose of `this` in a constructor?
Was this lesson helpful?