多态

1.多态的成员变量

父子类中出现同名变量:访问都看等于号左边

public class polymorphism {

    public static void main(String[] args) {
        Fu f = new Zi();
        System.out.println(f.num);//结果为4
        Zi z = new Zi();
        System.out.println(z.num);//结果为5
    }
}
class Fu{
    int num=4;
}
class Zi extends Fu{
    int num = 5;

2.多态的方法

多态成员方法
编译时期:参考引用变量所属的类,如果类中没有调用的方法,编译失败。
运行时期:参考引用变量所指的对象所属的类,并运行对象所属类中的成员方法。
简而言之:编译看左边,运行看右边

public class polymorphism {

    public static void main(String[] args) {
        Fu f = new Zi();
        f.show();//Zi_num=5
        Zi z = new Zi();
        z.show();//Zi_num=5
    }
}
class Fu{
    int num=4;
    void show(){
        System.out.println("Fu_num="+num);
    }
}
class Zi extends Fu{
    int num = 5;
    void show(){
        System.out.println("Zi_num="+num);
    }
}

多态静态方法
多态调用时:编译和运行都参考引用类型变量所属的类中的静态函数。
简而言之:编译和运行看等号的左边。其实真正调用静态方法是不需要对象的,静态方法通过类直接调用。

public class polymorphism {

    public static void main(String[] args) {
        Fu f = new Zi();
        f.show();//Fu static method run 
        Zi z = new Zi();
        z.show();//Zi static method run 
    }
}
class Fu{
    int num=4;
    
    static void show(){
        System.out.println("Fu static method run ");
    }
}
class Zi extends Fu{
    int num = 5;
    static void show(){
        System.out.println("Zi static method run ");
    }
}
结论:

1、对于成员变量和静态方法,编译和运行都看左边。
2、对于成员方法,编译看左边,运行看右边。

public class polymorphism {

    public static void main(String[] args) {
        Fu f = new Zi();
        f.show();//Fu  method run 4 
        Zi z = new Zi();
        z.show();//Fu  method run 4
    }
}
class Fu{
    int num=4;
    void show(){
        System.out.println("Fu  method run "+this.num);
    }
}
class Zi extends Fu{
    int num = 5;
}
public class polymorphism {

    public static void main(String[] args) {
        Fu f = new Zi();
        f.show();//Zi  method run 5
        Zi z = new Zi();
        z.show();//Zi  method run 5
    }
}
class Fu{
    int num=4;
    void show(){
        System.out.println("Fu  method run "+this.num);
    }
}
class Zi extends Fu{
    int num = 5;
    void show(){
        System.out.println("Zi  method run "+this.num);
    }
}

你可能感兴趣的:(多态)