Java中的继承真的发生了什么? [英] What really happens on inheritance in Java?

查看:90
本文介绍了Java中的继承真的发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个类 Parent Child ,以及 Child 继承自 Parent 。我在 Parent 中有三种方法,其中两种是公共的,一种是私有的。

Suppose I have two classes Parent and Child, and Child inherits from Parent. I have three methods in Parent, out of which two are public and one is private.

通常我们说所有非私有方法都被继承到 Child 类中,但我对确切发生的事情感到困惑。 Java是否在 Child 类中复制了这些方法,还是使用某种引用来维护关系?

Normally we say that all the non-private methods are inherited into the Child class, but I'm confused about exactly what happens. Does Java make a copy of the methods in the Child class, or does it use some kind of reference to maintain the relationship?

class Parent{
    // Private method
    private void method1(){
        System.out.println("In private method of Parent class");
    }
    void method2(){
    // calling private method
        method1();
    }
    void method3(){
    // calling private method
        method1();
    }
}

class Child extends Parent{

}

class MainClass{
   public static void main(String[] args){
       Child child = new Child();
       // calling non-private method which internally calls the private method
       child.method2();
   }
}


推荐答案


Java是否在Child类中复制了方法,或者它使用某种引用来维护关系?

Does Java makes copy of the methods in the Child class or it uses some kind of reference to maintain the relationship?

后者。请查看 invokespecial 。 Java递归地一次查找一个类的方法。调用第一个匹配方法。这就是调用虚拟(默认)方法比调用 final 方法慢的原因。

Latter. Take a look at invokespecial. Java recursively looks up methods one class at a time. The first matching method is called. This is why calling a virtual (default) method is slower than calling a final method.

一般来说,从包含该方法的类继承时,不会复制方法中的实际代码。

In general, the actual code within a method is not copied when you inherit from a class containing that method.

这篇关于Java中的继承真的发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆