覆盖接口的变量? [英] Overriding interface's variable?

查看:132
本文介绍了覆盖接口的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从各种Java书籍和教程中读到时,在接口中声明的变量是常量,不能被覆盖。



我做了一个简单的代码来测试它

  interface A_INTERFACE 
{
int var = 100;
}

类A_CLASS实现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();
}
}

并打印出
var = 99



var是否被覆盖?我完全糊涂了。感谢您的任何建议!






非常感谢大家!我对这个界面很新。 影子是理解这一点的关键词。我查阅相关材料并立即了解它。

解决方案

它没有被覆盖,但被遮蔽,因为常数会产生额外的混乱在界面中也是静态的。



试试这个:

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

你应该得到一个关于以非静态方式访问静态字段的编译时警告。 / p>

现在这个

  A_CLASS o = new A_CLASS(); 
System.out.println(o.var);
System.out.println(A_INTERFACE.var); //坏名字,顺便说一句,因为它是const


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.

解决方案

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

这篇关于覆盖接口的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆