java多态

多态方法调用允许相同基类的子类对相同的方法作出不同的响应。

实现动态的技术我们称为动态绑定,指在执行期间判断所引用对象的实际类型,根据其实际的类型调用其相应的方法。

多态的作用:消除类型之间的耦合关系。

多态存在的三个必要条件:有继承;有重写;父类应用指向子类对象。

向上转型

父类Animal

package test08;

public class Animal {
	public  void eat(){
		
	}
	public  void play() {
		
	}

}

子类Cat

package test08;

public class Cat extends Animal{

	@Override
	public void eat() {
		System.out.println("cat eat");
	}

	@Override
	public void play() {
		System.out.println("cat play");
	}

}

子类Dog

package test08;

public class Dog  extends Animal{

	@Override
	public void eat() {
		System.out.println("dog eat");
	}

	@Override
	public void play() {
		System.out.println("dog play");
	}
	

}

测试

package test08;

public class Test {
	public static void main(String[] args) {
		Cat cat=new Cat();
		Dog dog=new Dog();
		cat.eat();
		cat.play();
		dog.eat();
		dog.play();
	}

}

可以看到每当我们新增加一个子类就要增加新的方法,我们假设所有动物都有这两种方法,我们可以有更简单的方式去实现,增加一个action方法

package test08;

public class Action {
	public  void action(Animal animal){
		animal.eat();
		animal.play();
	}
}

结果测试

package test08;

public class Test1 {
	public static void main(String[] args) {
		Animal cat=new Cat();
		new Action().action(cat);
		Animal dog=new Dog();
		new Action().action(dog);
	}

}

这样以后想添加类似的子类方法不需要再一个个去直接调子类的方法了,因为action里面已经实现了子类的方法,我们只需要把父类的引用指向子类的对象即可。

经典题目
class A ...{  
         public String show(D obj)...{  
                return ("A and D");  
         }   
         public String show(A obj)...{  
                return ("A and A");  
         }   
}   
class B extends A...{  
         public String show(B obj)...{  
                return ("B and B");  
         }  
         public String show(A obj)...{  
                return ("B and A");  
         }   
}  
class C extends B...{}   
class D extends B...{}

问题:以下输出结果是什么? 

A a1 = new A();  
A a2 = new B();  
B b = new B();  
C c = new C();   
D d = new D();   
System.out.println(a1.show(b));   ①  
System.out.println(a1.show(c));   ②  
System.out.println(a1.show(d));   ③  
System.out.println(a2.show(b));   ④  
System.out.println(a2.show(c));   ⑤  
System.out.println(a2.show(d));   ⑥  
System.out.println(b.show(b));    ⑦  
System.out.println(b.show(c));    ⑧  
System.out.println(b.show(d));    ⑨

 答案:

①   A and A
②   A and A
③   A and D
④   B and A
⑤   B and A
⑥   A and D
⑦   B and B
⑧   B and B
⑨   A and D
posted @ 2017-05-16 23:42  Lost blog  阅读(212)  评论(0编辑  收藏  举报