如果具有相同名称的字段从两个源(类和接口)继承,将会发生什么 [英] what will happen if fields with same name inherites from two sources(class and interface)

查看:261
本文介绍了如果具有相同名称的字段从两个源(类和接口)继承,将会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

interface Int1{
    String str = "123";
}
class Pparent{
    String str = "123";  
}
class F extends Pparent implements Int1{       
}



无效代码



将主要方法添加到F类:

invalid code

add main method to F class:

class F extends Pparent implements Int1{
      public static void main(String[] args) {
        System.out.println(str);
    } 
}

出局


Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The field str is ambiguous

  at test.core.F.main(NullReferenceTest.java:45)


我不认为这两种变体都有惊人的不同。
我准备scjp并要求澄清所有相关情况。当我看到熟悉的问题时,我很乱。

I don't see striking differs beetwen both variants. I prepare to scjp and ask to clarify all related situations. When I see familiar question I am messed.

你能澄清一般规则吗?

推荐答案

标识符 str 有两个字段可以引用 - 从 Int1 继承的静态字段,以及从 Pparent 继承的实例。即使尝试使用来自静态上下文的实例1无效,该名称仍然可以解析。 (如果 Pparent.str 是静态的,您仍然会收到错误消息。)

There are two fields which the identifier str can refer to - a static one inherited from Int1, and an instance one inherited from Pparent. Even though it's invalid to try to use the instance one from a static context, the name can still be resolved. (If Pparent.str were static, you'd still get the error message.)

两个字段都没有隐藏另一方面,因为它们是从不同的父母那里继承而来的 - 所以名字含糊不清。编译器抱怨,因为它不知道你指的是哪个字段。

Neither field is hiding the other, because they're inherited from different parents - so the name is ambiguous. The compiler's complaining because it doesn't know which field you mean.

如果你想要一个来自 Int1 的那个,只要符合条件:

If you want the one from Int1, just qualify it:

System.out.println(Int1.str);

如果你想要一个来自 Pparent 的那个,你应该创建一个实例并将其转换为 Pparent ,以明确你 指的是接口字段:

If you want the one from Pparent, you should create an instance and cast it to Pparent to make it clear you're not referring to the interface field:

System.out.println(((Pparent) new F()).str);

显然这太可怕了,你应该避免首先陷入这种情况。这部分是通过将所有字段设为私有来实现的,除了常量。在超类和想要实现的接口中有两个具有完全相同名称的常量是非常罕见的。

Obviously this is horrible, and you should avoid getting into such situations in the first place. This is partly achieved by making all fields private, except constants. It's very unusual to have two constants with exactly the same name in both a superclass and an interface you want to implement.

这篇关于如果具有相同名称的字段从两个源(类和接口)继承,将会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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