Java Inheritance from Scratch: Stage‑2 AI Learning Notes
This note explains Java inheritance, covering the single‑inheritance class hierarchy, a Car class example, a ChildCar subclass that adds a load field, and eight key inheritance capabilities such as member reuse, method overriding, and constructor chaining, illustrating why inheritance improves code reuse and quality.
Inheritance Overview
In Java every class (except java.lang.Object) has exactly one direct superclass, forming a strict single‑inheritance hierarchy. If a class does not declare a superclass it implicitly extends java.lang.Object.
Example: Base class Car
public class Car {
// brand of the car
private String brand;
// color of the car
private String color;
// speed of the car
private double speed;
public Car(String brand, String color, double speed) {
this.brand = brand;
this.color = color;
this.speed = speed;
}
public String getBrand() { return brand; }
public String getColor() { return color; }
public double getSpeed() { return speed; }
public void setSpeed(double newSpeed) { this.speed = newSpeed; }
}The Car class models a generic vehicle with fields for brand, color and speed, and provides corresponding accessor methods.
Subclass ChildCar extending Car
public class ChildCar extends Car {
// additional field representing load capacity
public int load;
public ChildCar(int load, String brand, String color, double speed) {
super(brand, color, speed); // invoke superclass constructor
this.load = load;
}
public void setLoad(int load) { this.load = load; }
public int getLoad() { return load; }
} ChildCarinherits all members of Car and adds a new field load together with its setter and getter.
What a subclass can do
Inherited member variables can be accessed like any other variable.
Declaring a variable with the same name as an inherited one hides the superclass variable (generally discouraged).
A subclass may introduce new member variables that do not exist in the superclass.
Inherited methods can be invoked directly.
Method overriding allows a subclass to provide its own implementation with the same signature as a superclass instance method.
Method hiding occurs when a subclass declares a static method with the same signature as a superclass static method.
A subclass can add new methods that are absent in the superclass.
The superclass constructor can be called implicitly or explicitly with super inside the subclass constructor.
When the superclass contains complex, time‑consuming methods, inheritance enables reuse of already tested, high‑quality code without rewriting or retesting those methods.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
