【问题标题】:Why this code doesn't call the subclass? Inheritance in Java为什么这段代码不调用子类? Java中的继承
【发布时间】:2015-06-06 01:13:52
【问题描述】:
public class Parent {
    public  void printParent()
    {
        System.out.println("I am the Parent");
        System.out.println("----this is ::---" + this);
         this.printChild();
    }
    private void printChild()
    {
        System.out.println("This is my child");
    }
}

public class Child extends Parent {
    private void printChild()
    {
        System.out.println("I am the child");
    }
}

public class RelationshipTester {
    @Test
    public  void testRelation()
    {
        Child parent = new Child();
        parent.printParent();
    }
}

这是输出:-

我是家长

----这是 ::---datastructures.lists.inheritance.Child@1a692dec

这是我的孩子

对象的类型是 Child ,但它不调用子方法和父方法。我已经给了 this.printChild();

【问题讨论】:

  • 那是因为Child 没有printParent 方法
  • 是的,但它确实有 printChild 方法,所以当我调用 this.printChild() 它应该使用 child 方法,不是吗?
  • 私有方法不能被覆盖。 stackoverflow.com/questions/11976446/…

标签: java inheritance


【解决方案1】:

Parent 类中,您已将printChild 声明为私有...并调用它。不能覆盖私有方法。 Child 类中的 printChild 不为 Parent 类所知。

如果您要将 private 修饰符更改为 public,那么您有一个覆盖,并且您的示例应该输出您所期望的。


为什么 Java 不允许你覆盖私有方法?好吧,基本上,如果你能做到,那么就没有办法编写一个具有子类无法破坏的抽象边界的类。这将是(IMO)语言设计的一个主要缺点。

为什么 Java 不报告错误或警告?好吧,没有错误,因为根据 JLS,这是合法的 Java。至于警告...如果您单独编译Parent 没有问题,因为编写的代码是声明并使用私有方法。如果单独编译Child,编译器看不到Parent类中的私有方法。 (实际上,它甚至可能不存在于您正在编译的 Parent 的 .class 文件版本中。)仅当您同时编译 ParentChild可能编译器发现了一些奇怪的东西。

【讨论】:

  • 另外,private方法不能直接从其他类调用。
【解决方案2】:

关键字“this”指向当前类实例,这里是私有的 void printChild()。然后你在RelationshipTester 类中创建了一个Child 类的对象。这两个函数的范围是私有的,这意味着 to 仅限于该类。因此,它不会覆盖子类并会执行基类的方法。

【讨论】:

    【解决方案3】:

    private 方法不会被继承。当您调用printParent 时,您正在调用Parent 上的一个方法,而当该方法引用this 时,它引用的是该类的一个实例(Parent),它有自己的printChild 方法。将Parent#printChild 设为protected 方法应该会得到预期的结果。

    【讨论】:

      【解决方案4】:
      public class Child extends Parent {
          protected void printChild(){
              System.out.println("I am the child");
          }
      }
      

      使用受保护的,而不是私有的

      【讨论】:

      • 你没有弄错吗?受保护的必须放在Parent中?
      【解决方案5】:

      在这个程序中我们要记住两点:

      1. 如果我们为子类(这里是子类)创建一个对象,那么也会为超类创建内存。这意味着如果我们正在调用的方法在子类中找不到,那么 Java 虚拟机将转到父类并检查我们正在调用的方法,如果找到该方法,它将执行。如果在子类本身中找到该方法,它将不会转到父类。

      2. privatestaticfinal 方法不能被覆盖。

      【讨论】:

        【解决方案6】:

        由于该方法的作用域是私有的,它对其他类是不可见的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-23
          • 1970-01-01
          • 2016-10-05
          • 1970-01-01
          • 1970-01-01
          • 2022-01-04
          相关资源
          最近更新 更多