`

多态分析

 
阅读更多
/*
 *多态的例子分析
 *   
 */
public class ThinkingDifficult {
//       ab  B and A
	
	public static void main(String[] args) {			
		A a2 = new B();	
		B b = new B(); 
		System.out.println("ab    " + a2.show(b));
	}
}

class A {
	//public String show(B obj) {
	//	return ("A and B");
	//}	
	public String show(A obj) {
		return ("A and A");
	}
}
class B extends A {
	public String show(B obj) {
		return ("B and B");
	}
	//这是和多态有关,A a2 = new B();	调用不到show(B obj)方法,只能调用到show(A obj)或者show(A obj)重写之后的方法。
	public String show(A obj) {
		return ("B and A");
	}
	
} 

 对于A a2 = new B():

       它只能调用A类本身的方法,或者被子类重写的方法,调用不到子类的方法。

       所以System.out.println("ab   ” + a2.show(b));调用的结果是 B and A

      (B类中的show(B b)方法是方法的重载,不是重写)

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics