多态的练习

发布于:2023-01-21 ⋅ 阅读:(162) ⋅ 点赞:(0)

孟佳萱

测试代码

public class test {
	public static void main(String[] args) {
		A a1 = new A();
		A a2 = new B();
		B b = new B();
		C c = new C();
		D d = new D();
  
                          
                  //a1调用 A 里面的show方法
		System.out.println(a1.show(b));
                  //B是D的父类,父亲不能放到孩子里 -- (A obj) "A and A"
		System.out.println(a1.show(c));
                  //C和D 是兄弟关系 不能放到D里,放不下 --(A obj) "A and A"
		System.out.println(a1.show(d))
                      // D类型可以放到D里边 --(D obj) "A and D"
                 
				 //a2 可以使用A 里面的show方法,也可以使用子类重写的父类的方法
                 //  public String show(D obj) {
				  //     return "A and D";
			     // }public String show(A obj) {
				   //     return "B and A";
		         //   }    
		System.out.println(a2.show(b));
		//B是A的子类 所以使用show(A obj)----输出"B and A"
		System.out.println(a2.show(c));
		//C和D都是B 的子类 所以代表c和d是兄弟关系 使用show(A obj) ---输出"B and A"
		System.out.println(a2.show(d));
		//D直接使用show(D obj) ----输出"A and D"
			
		//b可以使用自己的方法 还可以使用继承过来父亲的方法 
		 //  public String show(D obj) {
		 //     return "A and D";
	     // }public String show(A obj) {
		   //     return "B and A";
        //   }        
        //public String show(Object obj){ return "B and B"; }
		System.out.println(b.show(b));
		//B是A的子类  使用show(A obj)  输出结果是A and D
		System.out.println(b.show(c));
		//C和D都是B 的子类 所以代表c和d是兄弟关系 使用show(A obj) ---输出"B and A"
		System.out.println(b.show(d));
		//D直接使用show(D obj) ----输出"A and D"

	}
}

分析

     a1调用 A 里面的show方法
	① System.out.println(a1.show(b));
      B是D的父类,父亲不能放到孩子里 -- (A obj) "A and A"
	②System.out.println(a1.show(c));
     C和D 是兄弟关系 不能放到D里,放不下 --(A obj) "A and A"
	③System.out.println(a1.show(d))
    D类型可以放到D里边 --(D obj) "A and D"
             
	a2 可以使用A 里面的show方法,也可以使用子类重写的父类的方法
      public String show(D obj) {
		    return "A and D";
		}
		public String show(A obj) {
		     return "B and A";
	     }    
	④ System.out.println(a2.show(b));
	B是A的子类 所以使用show(A obj)----输出"B and A"
	⑤System.out.println(a2.show(c));
	C和D都是B 的子类 所以代表c和d是兄弟关系 使用show(A obj) ---输出"B and A"
	⑥System.out.println(a2.show(d));
    D直接使用show(D obj) ----输出"A and D"
		
	b可以使用自己的方法 还可以使用继承过来父亲的方法 
	   public String show(D obj) {
		    return "A and D";
		}
		public String show(A obj) {
		     return "B and A";
	     }    
    public String show(Object obj){ return "B and B"; }
	⑦System.out.println(b.show(b));
	B是A的子类  使用show(A obj)  输出结果是A and D
	⑧System.out.println(b.show(c));
	C和D都是B 的子类 所以代表c和d是兄弟关系 使用show(A obj) ---输出"B and A"
	⑨System.out.println(b.show(d));
	D直接使用show(D obj) ----输出"A and D"

结果

孟佳萱


网站公告

今日签到

点亮在社区的每一天
去签到