Sub topic 2
Understand Inherited Members
What you will learn
In the last chapter you wrote a subclass with extends. This chapter explains what the subclass actually gets from its superclass. You will learn which members a subclass inherits and which ones it can't use by name. You will also learn why a private field can be part of an object even though the subclass can't read it.
This chapter assumes you know what a class, an object, a field, a method, and a constructor are. It also assumes you know the basic access modifiers public and private, and that you can compile and run a Java program.
What "inherited" means
A member is anything declared inside a class body. Fields, methods, and nested classes are members. A superclass is the class you extend. A subclass is the class that extends it.
When a subclass extends a superclass, it inherits some of the superclass's members. An inherited member behaves as if you had written it in the subclass yourself. You can use it by its simple name, and you can call it on a subclass object.
This is the main reason to use inheritance. You write shared code once in the superclass, and every subclass gets it for free.
Which members are inherited
Java decides by access modifier. An access modifier is a keyword such as public or private that controls who may use a member.
| Member | Inherited by the subclass? |
|---|---|
| `public` field or method | Yes, always |
| `protected` field or method | Yes, always |
| Package-private field or method (no modifier) | Only if the subclass is in the same package |
| `private` field or method | No, the subclass can't use it by name |
| Constructor | No, constructors are never inherited |
| `static` field or method | Yes, if the access modifier allows it |
A package is a named group of related classes. Package-private is the access you get when you write no modifier at all. A later chapter covers packages in detail. For now, all the examples keep every class in one package, so package-private members are inherited.
A worked example
This program has a Vehicle superclass and a Car subclass. The Vehicle class has one member of each access level.
class Vehicle {
String brand;
protected int speed;
private int mileage;
Vehicle(String brand) {
this.brand = brand;
}
void accelerate(int amount) {
speed += amount;
mileage += amount;
}
int getMileage() {
return mileage;
}
static String category() {
return "vehicle";
}
}
class Car extends Vehicle {
Car(String brand) {
super(brand);
}
void honk() {
System.out.println(brand + " honks at speed " + speed);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Volvo");
car.accelerate(30);
car.honk();
System.out.println(car.getMileage());
System.out.println(Car.category());
}
}The program prints:
Volvo honks at speed 30
30
vehicleHere is what happened, line by line.
Carnever declaresaccelerate, butcar.accelerate(30)works. The method is inherited fromVehicle.- Inside
honk, the code usesbrandandspeedby their simple names. Both are inherited, so no prefix is needed. Carnever declaresgetMileage, yetcar.getMileage()works. Inheritance givesCarthe public-facing way to read the value.Car.category()works because static methods are inherited too. You can call it through the subclass name.- The constructor
Vehicle(String brand)is not inherited. That is whyCarhas its own constructor, which callssuper(brand). The chapter on constructor chaining explains this call fully. For now, read it as "askVehicleto set up its part."
The class diagram
A class diagram shows classes and how they relate. In this one, a + means public, a # means protected, a - means private, and a ~ means package-private. The hollow arrow points from the subclass up to its superclass.
Private members: present but out of reach
The mileage field in Vehicle is private. Look at what happens if Car tries to use it:
class Car extends Vehicle {
Car(String brand) {
super(brand);
}
void reset() {
mileage = 0; // compile error
}
}The compiler reports an error similar to mileage has private access in Vehicle. Code outside Vehicle can't touch a private member, and a subclass counts as outside code.
There is a detail that surprises many beginners. The mileage field still exists inside every Car object. When you write new Car("Volvo"), Java builds one object that holds all of the Vehicle fields, private ones included. The accelerate method in Vehicle is allowed to update mileage, and it does so on the Car object.
So the rule is about access, not existence. The subclass can't name the private field, but the object still carries it.
The usual way to give a subclass controlled access is a public or protected method. In the example, getMileage() does this. Car objects can report their mileage, but only Vehicle code decides how mileage changes.
Constructors are not inherited
A constructor has the same name as its class, so a constructor named Vehicle could not make sense inside Car. For that reason, Java never passes constructors down.
This leads to a common error. Suppose Vehicle has only the constructor Vehicle(String brand), and you write this:
class Truck extends Vehicle {
// no constructor written
}The compiler rejects Truck. When you write no constructor, Java adds a default one that calls super() with no arguments. But Vehicle has no no-argument constructor, so the call fails. The fix is to write a constructor in Truck that calls super(brand), as Car does above.
Static members and inheritance
Static members belong to the class, not to any one object. They are inherited by name, so Car.category() compiles. Be careful, though. The subclass doesn't get its own copy of a static field. Car and Vehicle share the same single static field.
Static methods also behave differently from instance methods when a subclass declares one with the same signature. That is called hiding, not overriding. A later chapter covers the difference.
Checking what a subclass has
You can think of a subclass as having two groups of members:
- Members it declares itself, such as
honkinCar. - Members it inherits, such as
accelerate,speed, andbrand.
A useful test is to ask: "Could I call this on a Car object from some other class?" If the member is public, yes. If it is private in Vehicle, no. Package-private members work from the same package only.
Inheritance only goes one way. Vehicle doesn't get honk. A Vehicle variable can't call honk() unless the object it refers to is a Car and the variable's type allows it. A later chapter on subtypes returns to this point.
Common mistakes
- Expecting a private field to be usable in a subclass. The compiler reports a private access error. Use a getter or a protected member instead.
- Expecting constructors to be inherited. Every subclass needs a way to call a superclass constructor, either implicitly or with
super(...). - Thinking private means absent. The private field is stored in the object. Only direct access by name is blocked.
- Redeclaring a field in the subclass to work around access. If
Cardeclared its ownint mileage, it would create a second, separate field that hides the first. The two values would drift apart. Do not do this.
Summary
A subclass inherits the public and protected members of its superclass. It also inherits package-private members if it is in the same package. It does not inherit private members for direct use, and it never inherits constructors. Private fields still live inside the object, and superclass methods can use them on the subclass's behalf. Static members are inherited by name, but they are shared, not copied.
Exercise
A class Base has a private field count and a public method increment() that adds 1 to it. Class Derived extends Base and is in the same package. Can code inside Derived write count++? Can it call increment()? Explain what happens to count when you create a Derived object.
Show answer
Derived can't write count++, because count is private to Base and the compiler reports a private access error. Derived can call increment(), because that method is public and inherited, and it is allowed to change count. A Derived object still contains the count field, because the object holds every field of Base. Only direct access by name is blocked.
Exercise
Class Shape has only the constructor Shape(String color). You write class Circle extends Shape { } with no constructor. Why does this fail to compile, and how do you fix it?
Show answer
Constructors are not inherited. With no constructor written, Java adds a default one that calls super() with no arguments, but Shape has no no-argument constructor. To fix it, add a constructor to Circle that calls the existing one, for example Circle(String color) { super(color); }.