如果具有相同名称的字段从两个源(类和接口)继承,将会发生什么

编程入门 行业动态 更新时间:2024-10-25 04:19:52
本文介绍了如果具有相同名称的字段从两个源(类和接口)继承,将会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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.

更多推荐

如果具有相同名称的字段从两个源(类和接口)继承,将会发生什么

本文发布于:2023-11-05 19:12:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561624.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:将会   字段   接口   名称   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!