Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding interface's variable?

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.

like image 201
Alfred Zhong Avatar asked Jan 11 '12 04:01

Alfred Zhong


People also ask

Can we override interface variable?

You can NEVER override a variable. It doesn't matter if the variable is defined in an interface and/or a class, you simply can't override a variable.

Can you override an interface method?

Interface methods can very much be overloaded and overridden. The overriding just must happen in another interface, and is actually only done to specify more constraints in Javadoc. An example is the add method of java.

How do you override an interface property?

Use the Omit utility type to override the type of an interface property, e.g. interface SpecificLocation extends Omit<Location, 'address'> {address: newType} . The Omit utility type constructs a new type by removing the specified keys from the existing type. Copied!

Is overriding possible in interface in Java?

It is not mandatory to override the default method in Java. If we are using Only one interface in a Program then at a time we are using only a single default method and at that time Overriding is not required as shown in the below program: Java.


3 Answers

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
like image 164
Thilo Avatar answered Oct 15 '22 09:10

Thilo


You did not override the variable, you shadowed it with a brand-new instance variable declared in a more specific scope. This is the variable printed in your printx method.

like image 10
Sergey Kalinichenko Avatar answered Oct 15 '22 09:10

Sergey Kalinichenko


Default signature for any variable in an interface is

public static final ...

So you cannot override it anyhow.

like image 5
denis.solonenko Avatar answered Oct 15 '22 08:10

denis.solonenko