1、多态性的体现:
方法的重载和重写
对象的多态性
2、对象的多态性
向上转型:程序会自动完成
父类 父类对象 = 子类实例
向下转型:强制类型转换
子类 子类对象 = (子类)父类实例
public class A {
public void tell1() {
System.out.println("A----tell1");
}
public void tell2() {
System.out.println("A----tell2");
}
}
public class B extends A {
public void tell1() {
System.out.println("B----tell1");
}
public void tell3() {
System.out.println("B----tell3");
}
}
public class Demo {
public static void main(String[] args) {
// 向上转型
B b = new B();
A a = b;
a.tell1(); // 因为tell1方法被B类重写了,所以调用的是重写之后的方法
a.tell2();
// Output result:
// B----tell1
// A----tell2
// 向下转型
A a = new B(); // 注意此处是 new B(),因为如果 new A() ,那么new出来的对象与B是没有什么直接关系的,因此 进行强转时会报错:不能转换为B类型
B b = (B)a;
b.tell1();
b.tell2();
b.tell3();
// Output result:
// B----tell1
// A----tell2
// B----tell3
}
}
接口当中只允许存在抽象方法
interface USB {
void start(); // 可以省略 public abstract
void stop();
}