多态性的体现:方法的重载与重写;对象的多态性。
对象的多态性:
- 向上转型:程序会自动完成
父类 父类对象=子类实例 - 向下转型:强制类型转换
子类 子类对象=(子类)父类实例
class F{
void tell1()
{
System.out.println("F--tell1");
}
void tell2()
{
System.out.println("F--tell2");
}
public void tell3()
{
System.out.println("F--tell3");
}
}
class B extends F{
void tell1()
{
System.out.println("B-tell1");
}
void tell2()
{
System.out.println("B-tell2");
}
}
public class Jpro10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//向上转型
B b=new B();
b.tell1();
b.tell2();
b.tell3();
F a=b;
a.tell1();
a.tell2();
a.tell3();
//向下转型
F f=new B();//先发生向上转型,才能发生向下转型
B m=(B)f;
m.tell1();
m.tell2();
m.tell3();
}
}