Java三大特性之多态

多态

1. 概念:用父类类型来接受子类的对象Java通过方法重写来实现多态。

通过方法重写,子类可以重新实现父类的某些方法,使其具有自己的特征;

通过方法重写,相同类型的对象(变量),执行同一个方法变现出来的行为特征,称为多态

2. 多态的特点:

提高代码的复用性,简化代码

3. 不同对象对于相同方法表现出来不同的特征和响应;如:对于自行车和汽车,它 们都定义了刹车的方法,但是它们刹车方式却完全不同。

@copy

public class A {
public String show(D obj) {
return ("A and D");
}

public String show(A obj) {
return ("A and A");
}

}

public class B extends A{
public String show(B obj){
return ("B and B");
}

public String show(A obj){
return ("B and A");
}
}

public class C extends B{

}

public class D extends B{

}

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();

System.out.println("1--" + a1.show(b));
System.out.println("2--" + a1.show(c));
System.out.println("3--" + a1.show(d));
System.out.println("4--" + a2.show(b));
System.out.println("5--" + a2.show(c));
System.out.println("6--" + a2.show(d));
System.out.println("7--" + b.show(b));
System.out.println("8--" + b.show(c));
System.out.println("9--" + b.show(d));
}
}

原文地址:https://www.cnblogs.com/luoyunjian/p/10466384.html