gpt4 book ai didi

java - 重载时编译器错误 - Java

转载 作者:行者123 更新时间:2023-12-01 18:44:13 25 4
gpt4 key购买 nike

class parent
{
public void disp(int i)
{
System.out.println("int");
}
}

class child extends parent
{
private void disp(long l)
{
System.out.println("long");
}
}

class impl
{
public static void main(String... args)
{
child c = new child();
c.disp(0l); //Line 1
}
}

编译器提示如下

inh6.java:27: error: disp(long) has private access in child
c.disp(0l);

给定的输入是 0L,我试图重载子类中的 disp() 方法。

最佳答案

方法 disp() 被声明为私有(private)

private void disp(long l){System.out.println("long");}

因此,它仅在 child 类中可见,而不是在您尝试调用它的 impl 类中可见。将其可见性更改为公开或重新考虑您的设计。

如果您的问题是为什么看到 disp(long) 而不是 disp(int),这是因为您提供了 long > 方法调用的原始值。

 c.disp(0l); // the 'l' at the end means 'long'

访问修饰符的官方教程是here .

关于java - 重载时编译器错误 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18550250/

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