Sub topic 7
Access in Inheritance
Inheritance lets one Java class build on another. The new class can use suitable behavior from the existing class and add behavior of its own.
In this chapter, you will see which members a subclass can use, how its constructor works, and why an inherited method can use private state that the subclass cannot access directly.
The inheritance relationship
A class is a description of objects and their behavior. In inheritance, one class extends another:
- The superclass is the existing class.
- The subclass is the class that extends it.
- A member is a field or method declared in a class.
- An inherited member is a member that the subclass receives from its superclass under Java’s inheritance rules.
For example, a Dog can be an Animal. The Dog class can inherit animal behavior and add a method such as fetch.
Inheritance does not mean that the subclass can directly use every member in the superclass. Access rules still apply. In particular, private members are not inherited.
A complete example
Save this code in a file named InheritanceDemo.java:
class Animal {
private final String name;
Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void introduce() {
System.out.println("I am " + displayName() + ".");
}
private String displayName() {
return name;
}
protected void rest() {
System.out.println(name + " rests.");
}
void showGroup() {
System.out.println("An animal is a living thing.");
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
public void fetch() {
System.out.println(getName() + " fetches.");
}
public void dailyRoutine() {
introduce();
rest();
showGroup();
fetch();
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog("Milo");
dog.dailyRoutine();
Animal animal = dog;
animal.introduce();
}
}Compile and run it from the folder that contains the file:
javac InheritanceDemo.java
java InheritanceDemoThe output is:
I am Milo.
Milo rests.
An animal is a living thing.
Milo fetches.
I am Milo.All three classes are in the same source file. They also belong to the same package, which is a group of related Java classes. This file has no package declaration, so its classes are in Java’s unnamed package.
What Dog receives
The declaration class Dog extends Animal makes Dog a subclass of Animal.
In this example, Dog inherits these methods:
getNameandintroduce, which are public.rest, which is protected.showGroup, which has no access modifier. It is package-private, meaning it is available within its package.
The dailyRoutine method calls three inherited methods: introduce, rest, and showGroup. It also calls fetch, which is declared in Dog itself.
The private field name and the private method displayName are not inherited. Code in Dog cannot directly use them.
Private state and inherited behavior
A Dog object still has the state that Animal sets up for it. In this example, that includes the name stored by Animal. But the name field is private to Animal.
The Dog class uses the public getName() method when it needs the name:
getName()works insideDogbecause the method is public and inherited.- Writing
namedirectly insideDogwould cause a compile error. - Writing
super.nameinsideDogwould also cause a compile error.
A compile error is a problem Java reports before the program can run.
The same distinction applies to displayName(). It is private, so Dog cannot call it directly. Yet dog.dailyRoutine() can call the inherited introduce() method. That method was written in Animal, so it can call Animal’s private displayName() method.
This gives us an important rule: a subclass can use an accessible superclass method without gaining direct access to all the private members that the method uses.
Constructors and superclass state
A constructor sets up a new object. Constructors are not inherited, so Dog declares its own constructor:
Dog(String name)receives the name for the new dog.super(name)calls theAnimalconstructor with that name.- The
Animalconstructor assigns the name to its private field.
The word super refers to the superclass side of the current object. Calling super(name) does not create a second, separate Animal object. It runs the superclass constructor as part of setting up the new Dog object.
The field is declared final, which means it can be assigned only once. Here, the Animal constructor assigns it.
If you leave out a call to a superclass constructor, Java normally inserts super() for you. That call needs an accessible Animal constructor with no arguments. Our Animal class only declares a constructor that takes a String, so Dog supplies the name with super(name).
A superclass constructor must be accessible from the subclass. In this example, both constructors are package-private, and the classes are in the same package.
Access depends on the member and the context
An access modifier is a word such as public or private that controls where a declaration can be used. With no access modifier, a member is package-private.
The table describes what Dog can do with the members in the example.
| Member in `Animal` | Access | Can `Dog` use it directly? |
|---|---|---|
| `getName()` | Public | Yes. `Dog` inherits it. |
| `rest()` | Protected | Yes. `Dog` inherits it. |
| `showGroup()` | Package-private | Yes. `Dog` is in the same package as `Animal`. |
| `name` | Private | No. `Dog` can call `getName()` instead. |
| `displayName()` | Private | No. `Animal` can call it inside `introduce()`. |
| `Animal(String name)` | Package-private constructor | `Dog` can call it with `super(name)`, but does not inherit it. |
For members with package-private access, being in the same package matters. If these separate top-level classes were in different packages, Dog would not inherit Animal’s package-private showGroup() method.
Protected access also matters across packages, but it has extra rules about where and how a member is accessed. Do not treat protected as simply another spelling of public.
The declared type of a reference
A reference is a value that refers to an object. In the example, both dog and animal refer to the same Dog object:
dogis declared as typeDog.animalis declared as typeAnimal.
This assignment is allowed because a Dog is an Animal:
Animal animal = dog;
The declared type is the type written for a variable. Java uses that type when it checks which methods can be called through the variable.
Because introduce() is available on Animal, animal.introduce() works. But animal.fetch() would cause a compile error: fetch() is declared in Dog, not in Animal.
The object has not changed. The two variables simply offer different views of it. Through the Dog variable, the program can call dog.fetch().
Using `this` and `super`
Inside an instance method, this refers to the current object. An instance method is a method called on an object, such as dailyRoutine().
In our example, this.introduce() inside Dog would call the inherited method. The shorter call introduce() does the same thing here.
A subclass can also use super to refer to an accessible superclass member. For example, super.introduce() inside Dog would call the Animal version of that method.
Neither this nor super bypasses private access. In these separate top-level classes, this.name and super.name would both be invalid inside Dog.
Common mistakes
Expecting every superclass member to be inherited
Private members are not inherited. In the example, Dog can use getName(), but it cannot directly use name.
Check the member’s access before using it in a subclass. Also check the packages: a package-private member is not inherited from a superclass in a different package.
Expecting constructors to be inherited
Dog does not receive Animal(String name) as its own constructor. It declares Dog(String name) and calls super(name) to run the superclass constructor.
If Java tries to insert super() and the superclass has no accessible no-argument constructor, the code will not compile. Pass the required arguments to an accessible superclass constructor instead.
Calling a subclass method through a superclass variable
Even when animal refers to a Dog, its declared type is Animal. A call through animal must be available on Animal. Use the dog variable to call fetch() in this example.
Using inheritance only to reuse a few methods
A subclass should represent a kind of its superclass. A dog is an animal, so the relationship fits. Before writing extends, ask whether objects of the new class should be usable as objects of the existing class. If that relationship does not make sense, inheritance may be the wrong choice.
Practice
Exercise
Why can Dog call introduce() even though introduce() calls the private method displayName()?
Show answer
introduce() is public and inherited by Dog. Its code is declared in Animal, where it is allowed to call Animal’s private displayName() method. Dog cannot call displayName() directly.
Exercise
In the example, what happens if you remove super(name) from the Dog constructor? Why?
Show answer
The code will not compile. Java tries to call super(), but Animal does not declare a no-argument constructor. Its constructor requires a String.
Exercise
After Animal animal = dog;, can you call animal.fetch()? Can you call dog.fetch()?
Show answer
animal.fetch() does not compile because the declared type Animal has no fetch() method. dog.fetch() works because dog is declared as type Dog, which has that method.
Exercise
If Dog and Animal were separate top-level classes in different packages, would Dog inherit the package-private showGroup() declared in Animal?
Show answer
No. A subclass in a different package does not inherit that package-private member from its superclass.