简体   繁体   English

Java中的继承不符合我的预期

[英]inheritance in java does not work the way I expected

I have the following class: 我有以下课程:

public class X {
    public void A() {
        B();
    }

    private static void B() {
        System.out.println("111111111");
    }
}

Now I have the following inherited class Z: 现在,我有以下继承的类Z:

public class Z extends X {

    private static void B() {
        System.out.println("22222222");
    }
}

now if I do 现在,如果我愿意

Z myClass = new Z();
Z.A();

I will get: 111111111 as a result. 我会得到:111111111结果。 (Also, eclipse tells me that B() in the inherited class is never called). (此外,eclipse告诉我,从不调用继承类中的B())。

Why? 为什么? And how can I run the inherited B method? 以及如何运行继承的B方法?

The B methods are static . B方法是静态的 When you call the method A it uses the implementation of class B (because that's where the method A is defined). 当您调用方法A它将使用类B的实现(因为这是方法A的定义位置)。 Class B is not aware of the existence of class Z and cannot call a method of class Z . B不知道类Z的存在,因此无法调用类Z的方法。

Because the method is static, it's not overridden upon inheriting from B . 由于该方法是静态的,因此从B继承时不会覆盖该方法。 Polymorphism only works with instances of a class. 多态仅适用于类的实例。 Static method does not play the polymorphism game and cannot be overridden. 静态方法不会玩多态游戏,因此不能被覆盖。

Change access modifier of method from private static to protected 将方法的访问修饰符private static更改为protected

If you re-define base class non-static & non-private method in derived class, it's called overriding . 如果您在派生类中重新定义基类的非静态和非私有方法,则称为overriding

If you re-define base class static method in derived class, it's called method hiding or method shadowing . 如果您在派生类中重新定义基类静态方法,则称为方法隐藏或方法阴影

You have done hiding rather overriding in your example. 您已经在示例中完成了隐藏而不是覆盖。

Have a look at this SE Question 看看这个SE问题

You're calling X's inherited A method, and this calls its private B method. 您正在调用X的继承A方法,这将调用其私有B方法。

private methods and attributes are not inherited. private方法和属性不会被继承。

It looks like you are overriding method B() in class Z but method B() is not overridden here. 看来您正在覆盖类Z中的方法B(),但此处未覆盖方法B()。 Since B() is static so class A and class Z has there own method B(). 由于B()是静态的,因此类A和类Z具有自己的方法B()。 Scope of all the Static methods and variables are class level not an object level. 所有Static方法和变量的范围都是类级别而不是对象级别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM