Sub topic 2
Understand Inherited Members
When one class extends another, the new class gets a copy of the old class's parts for free. This is called inheritance. The class being extended is the superclass. The new class is the subclass. The parts the subclass receives are its inherited members. A member is either a field (a variable inside a class) or a method (a named action inside a class).
Inheritance saves work. You write a common field or method once in the superclass. Every subclass can then use it.
A First Example
Here is a superclass called Animal and a subclass called Dog:
class Animal {
String name;
protected int age;
void eat() {
System.out.println(name + " is eating.");
}
}
class Dog extends Animal {
void bark() {
System.out.println(name + " says woof."); // inherited field
eat(); // inherited method
age = 3; // inherited field
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.name = "Rex";
dog.bark();
dog.eat();
}
}The Dog class never declares name, age, or eat(). It still uses them as if it did. The output is:
Rex says woof.
Rex is eating.
Rex is eating.Which Members Are Inherited?
Access modifiers (keywords like public and private) control what a subclass can use. The table shows the common cases.
| Member kind | Inherited? | Usable by name in the subclass? |
|---|---|---|
| `public` field or method | Yes | Yes |
| `protected` field or method | Yes | Yes |
| No modifier (package access) | Yes, if both classes are in the same package | Yes, if in the same package |
| `private` field or method | Yes, but hidden | No |
| Constructor | No | No |
A private member belongs to the superclass only. If Dog tries to call a private method from Animal, the code will not compile.
> Private members are not removed from the subclass object. They are simply locked. The subclass code cannot name them.
Constructors are also not inherited. A constructor builds an object of one specific class. You will learn how a subclass calls its superclass constructor in a later chapter.
Try It Yourself
Exercise
Look at this code. Which lines compile inside the Car class? class Vehicle { int wheels; private String vin; void honk() { System.out.println("Beep!"); } } class Car extends Vehicle { void test() { wheels = 4; // line A honk(); // line B vin = "ABC"; // line C } }
Show answer
Lines A and B compile. Field wheels and method honk() are inherited with normal access. Line C does not compile, because vin is private in Vehicle and Car cannot use it by name.