Java多态陷阱之只有普通方法是多态的,字段和静态方法没有多态

2023年5月29日 563点热度 0人点赞 0条评论

一、Java字段是没有多态的,只有普通方法是多态的。

当父类的引用指向子类对象,通过直接访问 得到的结果是父类身上字段的值。

如果是通过普通方法获取字段,则获取到的是子类字段的值。


public class Father {

    public int field = 0;

    public int getField(){
        return field;
    }
}

class SubObject extends Father{
    public int field = 1;

    public int getField(){
        return field;
    }

    public int getFatherField(){
        return super.getField();
    }

    public static void main(String[] args) {
        Father father = new SubObject();
        System.out.println("Father field---"+father.field); //Father field---0
        System.out.println("Father getField---"+father.getField()); //Father getField---1

        SubObject subObject = new SubObject();
        System.out.println("subObject field---"+subObject.field); //subObject field---1
        System.out.println("subObject getField---"+subObject.getField()); //subObject getField---1
        System.out.println("subObject getFatherField---"+subObject.getFatherField()); //subObject getFatherField---0
    }
}

二、Java静态方法没有多态


public class Father {

    public static void staticGet(){
        System.out.println("Father staticGet ...");
    }

    public void notStaticMethod(){
        System.out.println("Father notStaticMethod ...");
    }
}

class SubObject extends Father{

    public static void staticGet(){
        System.out.println("SubObject staticGet ...");
    }


    @Override
    public void notStaticMethod(){
        System.out.println("SubObject notStaticMethod ...");
    }

    public static void main(String[] args) {
        Father father = new SubObject();
        father.staticGet(); //Father staticGet ...
        father.notStaticMethod(); //SubObject notStaticMethod ...

        SubObject subObject = new SubObject();
        subObject.staticGet(); //SubObject staticGet ...
        subObject.notStaticMethod(); //SubObject notStaticMethod ...
    }
}

小小调酒师

此刻打盹,你将做梦; 此刻学习,你将圆梦。 个人邮箱:shellways@foxmail.com

文章评论