【问题标题】:Java: Why is the parent class methods visible to the derived class?Java:为什么派生类可以看到父类方法?
【发布时间】:2021-02-28 16:50:03
【问题描述】:
 class Base {
    public void display(int n){ 
        System.out.println(n); 
        
    }}
 class Derived extends Base{ 
    public void display(){ //Line-1 
        System.out.println("display overloaded"); 
            
        }}
public class Tester { 
    public static void main(String[] args){ 
        Derived ref = new Derived(); 
        ref.display(10); //Line-2 
                }}

为什么这段代码有效?父类方法如何对子类可见和可用?第 2 行不应该抛出一个错误,说没有这样的方法,或者定义的方法不应该有任何参数。

【问题讨论】:

  • 你没有覆盖。您正在重载

标签: java class inheritance methods java-8


【解决方案1】:

这些是不同的方法,要覆盖一个方法,您必须具有相同的方法签名

@Override
public void display(int n){ 
  System.out.println("display overloaded"); 
}

还要添加@Override 以表明您正在覆盖基本方法

请注意,您不能真正删除方法,只需覆盖它(或以您的示例重载)

【讨论】:

    【解决方案2】:

    在java中,所有带有publicprotected访问修饰符的方法和变量都是从父类继承到子类的。由于您的输入参数为int display(int n)的显示方法也是从父类Base继承到Derived。结果方法也可用于基类。

    当您在没有参数display()Derived 类中创建显示方法时,您实际上是在使用方法重载概念(而不是覆盖)。因此,在您的 Derived 类中,实际上您有两个具有相同名称(不同参数)display()display(int n) 的方法。

    这就是为什么你没有得到没有这样的方法或者定义的方法不应该有任何参数

    【讨论】:

      【解决方案3】:

      派生的方法正在覆盖其超类中的方法,但它没有接受任何参数,但是您为派生的子类提供了一个参数,因此它会找到哪个方法正在接受参数并且它找到了,这就是为什么它没有给出错误

      【讨论】:

        猜你喜欢
        • 2013-10-08
        • 2020-08-23
        • 2021-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2021-12-20
        相关资源
        最近更新 更多