私有成员有没有被继承?那构造函数呢?

首先给出结论,私有成员会被继承,但不能被显式调用,构造函数不会被继承。这个问题是我这几天在某网站上面刷题遇到的,感觉比较有意思。我们来验证一下。怎么验证呢,通过反射!

直接创建两个类,父类A,子类B:

class A {
private void prA() {
System.out.println("父类私有");
}
}

class B extends A {
}

然后测试下:

    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {

        //由子类得到父类的方法数组
        Class bClass = Class.forName("B");
        Method[] aMethods = bClass.getSuperclass().getDeclaredMethods();
        //设置私有方法可以被访问
        AccessibleObject.setAccessible(aMethods,true);
        for (int i = 0; i < aMethods.length; i++) {
            aMethods[i].invoke(new B(), null);
        }

        Class aClass = bClass.getSuperclass();
    }

结果:父类私有

最后引用下官方的一句话关于构造函数的:

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.   [子类从其父类继承所有成员(字段,方法和嵌套类)。 构造函数不是成员,所以它们不被子类继承,但是可以从子类调用超类的构造函数。]

 

posted @ 2019-06-16 16:11  junlancer  阅读(696)  评论(0编辑  收藏  举报