Java基础之多态

1.多态:父类引用指向子类对象

2.多态有一个显著的特点就是不能使用子类的特有方法,父类中没有的方法就不可以使用,若想使用子类的特有功能,可以把父类引用强制转化程子类引用,即向下转化

3.代码演示:

class   Fu{
    public Fu() {
        System.out.println("父类构造方法");
    }
    int age=50;
    public void show(){
        System.out.println("woshifuqin");
    }
    public static void method(){
        System.out.println("静态父");
    }
}
class Zi extends Fu{
    public Zi(){
        System.out.println("子类构造方法");
    }
    int age=20;
    public void show(){
        System.out.println("woshizi");
    }
    public static void method(){
        System.out.println("静态子");
    }
    public void ce(){
        System.out.println("多态的弊端是不能使用子类的特有功能");
    }
}
public class PointToDemo {
    public static void main(String[] args) {
        Fu f=new Zi();
        System.out.println(f.age);//父类引用指向子类对象,变量是以父类为准
        f.show();//重写的方法以子为准
        f.method();//静态方法与类相关,算不上重写,所以访问的还是父类
        //f.ce();
        Zi z= (Zi) f;
        z.ce();//向下转型
    }
}

 

posted @ 2020-07-22 10:59  sumilemei  阅读(118)  评论(0)    收藏  举报