In this lesson, you will learn
Using getters and setters in the context of inheritance in Java, the subclasses can interact with their superclass’s private fields in a controlled manner.
When a subclass extends a superclass, it inherits its methods, which include any getter and setter methods defined in the superclass.
This allows the subclass to access and modify private fields of the superclass without directly accessing them, adhering to the principles of encapsulation and inheritance.
Let’s consider an example with two classes: Vehicle as the superclass and Car as the subclass.
In this example, Vehicle will have private fields that are common to all vehicles, such as make and year, along with corresponding getter and setter methods.
The Car class will extend Vehicle and add more specific fields related to cars, such as model.
package ch9.l3.accessvehicle;
class Vehicle {
private String make;
private int year;
// Getter for 'make'
public String getMake() {
return make;
}
// Setter for 'make'
public void setMake(String make) {
this.make = make;
}
// Getter for 'year'
public int getYear() {
return year;
}
// Setter for 'year'
public void setYear(int year) {
this.year = year;
}
}
class Car extends Vehicle {
private String model;
// Getter for 'model'
public String getModel() {
return model;
}
// Setter for 'model'
public void setModel(String model) {
this.model = model;
}
/* Example method to demonstrate accessing superclass
* fields via getters and setters
*/
public void updateVehicleInfo(String make, int year, String model) {
setMake(make); // Calls the setter method from Vehicle class
setYear(year); // Calls the setter method from Vehicle class
this.setModel(model); // Calls the Car class's own setter
}
}
public class AccessVehicle {
public static void main(String[] args) {
// Create a new Car object
Car myCar = new Car();
myCar.setMake("Honda");
myCar.setYear(2019);
myCar.setModel("Civic");
// Access superclass methods via subclass object
System.out.println("Make: "+myCar.getMake()); //Accesses Vehicle's getMake
System.out.println("Year: "+myCar.getYear()); //Accesses Vehicle's getYear
System.out.println("Model: "+myCar.getModel()); //Accesses Car's getModel
// Update vehicle information
myCar.updateVehicleInfo("Toyota", 2021, "Corolla");
System.out.println("nAfter update:");
System.out.println("Make: "+myCar.getMake()); // Toyota
System.out.println("Year: "+ myCar.getYear()); // 2021
System.out.println("Model: "+myCar.getModel()); // Corolla
}
}
Make: Honda Year: 2019 Model: Civic After update: Make: Toyota Year: 2021 Model: Corolla