从子类方法保护超类方法

Fáb*_*rez 2 java methods inheritance class

是否有可能一个类有一个只能被它的对象调用并为子类对象隐藏的方法?例如:

class ClassOne {
    ... // attributes

    public void doSomething() { ... }
}

class ClassTwo extends ClassOne {
    ... // attributes and methods
}

ClassOne c1 = new ClassOne();
c1.doSomething(); // ok to call

ClassTwo c2 = new ClassTwo();
c2.doSomething(); // forbidden
Run Code Online (Sandbox Code Playgroud)

我知道这似乎是遗传的奇怪思考,但它有可能吗?

PS:这个问题的目的只是为了更多地了解OO编程的继承.

Bor*_*ris 5

这样做会破坏继承权,这是不可能的.想一想

ClassOne c2 = new ClassTwo();
c2.doSomething(); // what to do?
Run Code Online (Sandbox Code Playgroud)

这必须起作用,因为ClassTwo ClassOne.编辑:至少是必须编译,如果方法被覆盖并做其他事情取决于您的设计.但是你不能让编译器在这上面产生错误.