Inheritance with a variable in java

不打扰是莪最后的温柔 提交于 2019-12-05 19:37:27

You cannot override attribute, you can only override method:

public class A{
    private int i=10;

    public void name(){   
        System.out.println("A");
    }

    public int getI(){
        return i;
    }
}

public class B extends A{
    private int i=20;

    public void name(){        
        System.out.println("B");
    }

    @Override
    public int getI(){
        return i;
    }
}  

public class HelloWorld { 

    public static void main(String[] args){
        A a = new B();
        a.name();
        System.out.println(a.getI());
    }

}

In your example, you define variable a as type A so the i value in B is ignored.

You are absolutely correct. Methods are overridden in Java if the parameter list and function names are identical, and the return types are covariant.

i in the base class is simply shadowed: a.i refers to the i member in the base class, since the type of the reference a is an A, even though it refers to a B instance.

In Java instance variables cannot be overridden, only methods can be overridden. When we declare a field with same name as declared in super class then this new field hides the existing field. See this Java doc Hiding Fields.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!