gpt4 book ai didi

java - 具有方法名称和与外部类不同的签名的内部类

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:19:01 25 4
gpt4 key购买 nike

我知道如何让这段代码工作,但我很好奇为什么编译器无法弄清楚调用是对外部类方法的调用:

public class Example {
public void doSomething(int a, int b)
{
}

public class Request
{
public int a;
public int b;

public void doSomething()
{
doSomething(a,b); // Error. Fix: Example.this.doSomething(a,b);
}
}
}

这是否有比保护编码人员不犯错误更深层次的设计原因?

最佳答案

根据语言定义,外部类方法在内部类中是不可见的,因为它被隐藏

影子是基于名字而不是签名。这是一件的事情。

考虑替代方案。您可以隐藏方法重载的子集。其他人可能会尝试更改调用中的参数,以调用其他重载方法之一。简单地更改参数可能会导致接收者对象发生变化。这将是令人惊讶的,并且可能会花费时间进行调试。

来自 Java 语言规范,6.3.1:

Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity. A declaration d of a type named n shadows the declarations of any other types named n that are in scope at the point where d occurs throughout the scope of d.

...

A declaration d is said to be visible at point p in a program if the scope of d includes p, and d is not shadowed by any other declaration at p. When the program point we are discussing is clear from context, we will often simply say that a declaration is visible.

关于java - 具有方法名称和与外部类不同的签名的内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7600497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com