Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As I read from various Java book and tutorials, variables declared in a interface are constants and can't be overridden.

I made a simple code to test it

interface A_INTERFACE
{ 
    int var=100; 
}

class A_CLASS implements A_INTERFACE
{ 
    int var=99; 
    //test
    void printx()
    {
        System.out.println("var = " + var);
    }
}

class hello
{

    public static void main(String[] args)
    {
        new A_CLASS().printx();
    }
}

and it prints out var = 99

Is var get overridden? I am totally confused. Thank you for any suggestions!


Thank you very much everyone! I am pretty new to this interface thing. "Shadow" is the key word to understand this. I look up the related materials and understand it now.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
86 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is not overridden, but shadowed, with additional confusion because the constant in the interface is also static.

Try this:

A_INTERFACE o = new A_CLASS();
System.out.println(o.var);

You should get a compile-time warning about accessing a static field in a non-static way.

And now this

A_CLASS o = new A_CLASS();
System.out.println(o.var);
System.out.println(A_INTERFACE.var);  // bad name, btw since it is const

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...