黑马程序员技术交流社区
标题:
实现的接口出现重名常量
[打印本页]
作者:
sd110572
时间:
2013-12-10 18:33
标题:
实现的接口出现重名常量
本帖最后由 sd110572 于 2013-12-10 20:14 编辑
public class InterfaceDemo {
public static void main(String[] args) {
System.out.println(Demo.B);
}
}
interface Inter1{
public static final int A=0;
}
interface Inter2{
public static final int A=1;
public static final int B=2;
}
class Demo implements Inter1,Inter2{
}
复制代码
上面代码编译通过,可以打印接口2的B值,可是该如何打印A值呢?
接口1和接口2都不行,会出现 字段 Demo.A 有歧义。
我的意思是那 Demo到底继承了那个接口的A值,不是静态一加载就有了么,
那么虽然不能调用,Demo 到底有没有那个A值?
作者:
ZHMing
时间:
2013-12-10 18:52
本帖最后由 ZHMing 于 2013-12-10 18:54 编辑
因为接口里的常量被static修饰符修饰了,类启动时都已经加载过了,想调用直接打接口名.常量名就可以输出了。
public class InterfaceDemo {
public static void main(String[] args) {
System.out.println(Demo.B);
System.out.println(Inter1.A);
System.out.println(Inter2.A);
System.out.println(Inter2.B);
}
}
interface Inter1{
public static final int A=0;
}
interface Inter2{
public static final int A=1;
public static final int B=2;
}
class Demo implements Inter1,Inter2{
}
复制代码
作者:
雪飘舞
时间:
2013-12-10 18:57
本帖最后由 雪飘舞 于 2013-12-10 19:16 编辑
无法打印A的值,语法上存在错误,虚拟机无法识别。同一个类实现的多个接口之间,不能出现静态的相同内容
public class InterfaceDemo {
public static void main(String[] args) {
System.out.println(Demo.B);//首先调用Demo.B,会去Dmeo中查找是否有B,没有的话会去
//Demo实现的接口Inter2、Inter1中查找。找到后打印B的值
//System.out.println(Demo.A);//但如果打印的是Demo.A的话,当去Demo实现的接口Inter2、Inter1寻
//找时发现有2个静态且不可改变的A的值时,虚拟机就不知道该去运行哪
//个,因此编译时就会报错(即语法上已经出现了错误)
}
}
interface Inter1{
public static final int A=0;
}
interface Inter2{
public static final int A=1;
public static final int B=2;
}
class Demo implements Inter1,Inter2{//实现了2个接口
}
作者:
kongling
时间:
2013-12-10 19:03
本帖最后由 kongling 于 2013-12-10 19:07 编辑
Demo里两个A值都存在,但是Demo.A直接这样的话,编译器不知道应该使用接口Inter1里的A,还是接口Inter2的A,出现歧义。
可以像下面的方式来使用就可以:
Inter1 demo1=new Demo();
Inter2 demo2=new Demo();
int a=demo1.A;
System.out.println(a);
int b=demo2.A;
System.out.println(b);
复制代码
作者:
胡永城
时间:
2013-12-10 19:28
本帖最后由 胡永城 于 2013-12-10 19:30 编辑
Demo里有A的值,而且是两个都有,所以这就麻烦了,Demo.A的话,虚拟机都不知道加在哪个了,所以需要指明。
interface Inter1{
public static final int A=0;
public int c = 0;
public int d = 0;
}
interface Inter2{
public static final int A=1;
public static final int B=2;
public int c = 0;
}
class Demo implements Inter1,Inter2{
public static void main(String arg[]){
System.out.println(Demo.B);//Demo实现接口的静态常量参数(类变量)
//System.out.println(Demo.A);//报出错误,虚拟机不能识别A是来自于哪一个接口
System.out.println(Inter1.A);
System.out.println(Inter2.A);
/*
* 不但静态的变量是这样,成员变量也会这样
*/
System.out.println(Demo.d);//Demo实现接口的变量参数(成员变量)
//System.out.println(Demo.c);//报出错误,虚拟机不能识别A是来自于哪一个接口
System.out.println(Inter1.c);//指明来自于哪一个接口
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2