6.2 Inheritance and Overriding
Inheritance lets one class receive fields and methods from another class. It is useful for "is a" relationships: Food is a Product, and Drink is also a Product.
Inheritance
The parent class stores shared features, and subclasses add differences.
Loading interactive lab...
java
class Product {
private String name;
private double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
String getName() {
return name;
}
double getPrice() {
return price;
}
}
class Food extends Product {
private int calories;
Food(String name, double price, int calories) {
super(name, price);
this.calories = calories;
}
int getCalories() {
return calories;
}
}
class Drink extends Product {
private String size;
Drink(String name, double price, String size) {
super(name, price);
this.size = size;
}
String getSize() {
return size;
}
}super(name, price) calls the parent constructor so shared name and price are initialized first.
Loading concept check...
Overriding
When a subclass needs to change inherited behavior, it can override a method. A common example is overriding toString().
Loading interactive lab...
java
class Product {
private String name;
private double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return String.format("%s ($%.2f)", name, price);
}
}
class Food extends Product {
private int calories;
Food(String name, double price, int calories) {
super(name, price);
this.calories = calories;
}
@Override
public String toString() {
return String.format("Food: %s, %d Kcal", super.toString(), calories);
}
}
public class ProductDemo {
public static void main(String[] args) {
Food food = new Food("Cheeseburger", 5.45, 302);
System.out.println(food);
}
}Output:
text
Food: Cheeseburger ($5.45), 302 KcalThe subclass toString() can call super.toString() to reuse the parent string format.
Loading concept check...
Reusing Parent Logic While Overriding
Overriding does not always mean throwing away the parent code. Often, a subclass wants to add information before or after the parent result, so the overridden method calls super.
java
@Override
public String toString() {
return String.format("Food: %s, %d Kcal", super.toString(), calories);
}Loading concept check...
Loading practice...