Java late binding后期绑定与polymorphism多态的结合

若没有学习继承,可先前往以下网址先学习inheritance:

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)

Example: Create an array of various university people and print
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值