若没有学习继承,可先前往以下网址先学习inheritance:
Motivation: Consider the following example:
Faculty carol = new Faculty("Carol Tuffteacher", 458, 1995);
Person p = carol;
System.out.println(p.toString());
• Q: Should this call Person's toString or Faculty's toString?
• A: There are good arguments for either choice:
Early (static) binding: The variable p is declared to be of type Person. Therefore, we should call the Person’s toString.
Late (dynamic) binding: The object to which p refers was created as a “new Faculty”.
Therefore, we should call the Faculty's toString.
Pros and cons: Early binding is more efficient, since the decision can be made at compile time. Late binding provides more flexibility.
• Java uses late binding (by default): so Faculty toString is called (Note: C++ uses early binding by default.)
• Late (or dynamic) binding: method that is called depends on an object’s actual type, and not the declared type of the referring variable.
Java's late binding makes it possible for a single reference variable to refer to objects of many different types. Such a variable is said to be polymorphic (meaning having many forms)
public class Polymorphism {
public static void main(String[] args) {
Person[] list = new Person[3];
list[0] = new Person("Col. Mustard", 10);
list[1] = new Student("Ms. Scarlet", 20, 1998, 3.2);
list[2] = new Faculty("Prof. Plum", 30, 1981);
for (int i = 0; i < list.length; i++) {
System.out.println(list[i].toString());
}
}
}
输出为:
[Col. Mustard] 10
[Ms. Scarlet] 20 1998 3.2
[Prof. Plum] 30 1981