5.1.3 Subclass Constructors
The fact that an object variable can refer to multiple actual types is called polymorphism. Automatically selecting the appropriate method at runtime is called dynamic binding.
5.1.5 Polymorphism
The "is-a" rule states that every object of the subclass is an object of the superclass.
For example, you can assign a subclass object to a superclass variable.
Employee e;
e = new Employee();
e = new Manager();
In the Java programming language, object variables are polymorphic.
Manager boss = new Manager();
Employee[] staff = new Employee[3];
staff[0] = boss;
In this case, the variables staff[0]
and boss
refer to the same object. However, staff[0]
is considered to be only an Employee
object by the compiler.
boss.setBonus(5000); // OK
staff[0].setBonus(5000); // Error, because the Employee class does not have a setBonus method.
5.1.7 Preventing Inheritance: Final Classes and Methods
Classes that can not be extended are called final classes.
public final class Executive extends Manager {
...
}
You can also make a specific method in a class final
. If you do this, then no subclass can override that method. (All methods in a final class are automatically final.)
5.1.9 Abstract Classes
A class with one or more abstract methods must itself be declared abstract.
public abstract class Person {
...
public abstract String getDescription();
}
In addition to abstract methods, abstract classes can have fields and concrete methods.
public abstract class Person {
private String name;
public Person(name) {
this.name = name;
}
public abstract String getDescription();
public String getName() {
return name;
}
}
Abstract classes cannot be instantiated.
Note that you can still create object variables of an abstract class, but such a variable must refer to an object of a nonabstract subclass.
Person p = new Student("Vince Vu", "Economics");
Here p is a variable of the abstract type Person
that refers to an instance of the nonabstract subclass Student
.
5.1.10 Protected Access
default
vs public
vs private
vs protected
Youtube上面有一个讲得很好的视频:Java Access Modifiers - Learn Public, Private, Protected and Default
总结就是:
1. Accessible in the class only (private
).
2. Accessible by the world (public
).
3. Accessible in the package and all subclasses (protected
).
4. Accessible in the package - the (unfortunate) default
.