java - 如何在调用方法时绕过java中的继承

标签 java inheritance oop

    class Super {

        public void anotherMethod(String s) {
            retValue(s)
        }


        public String retValue(String s) {
            return "Super " + s;
        }

    }

    class Sub extends Super {

        public void anotherMethod(String s) {
            retValue(s)
        }

        public String retValue(String s) {
            return "Sub " + s;
        }

    }

if suppose in main,

Super s = new Sub();
s.anotherMethod("Test");

Output will be, Sub Test

谁能帮我告诉我如何使用 ma​​in 中给定的序列 获得输出Super Test

And let me explain why I want this, say I have a class which has method test() and it can be overriden by sub classes, in some cases I want the overriden test() and in some cases I want the test() of super class itself, there are many ways to do this, best suggestions will be helpful.

最佳答案

你为什么要这样做??

多态性的全部要点是调用正确的方法而不需要知道你有哪种实例......

关于java - 如何在调用方法时绕过java中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/510976/

相关文章:

php - PHP 中的值对象

java - (编程到接口(interface) v/s 使用具体类)当只有一个具体类时

java - ApplicationEventPublisher NullPointerException

java - 如何从给定值获取平均值

c++ - 在派生类中重新定义 typedef?

c++ - 为什么函数返回垃圾值?

python - 让父方法返回子类实例

java - Fisher-Yates (java) 与 Collections.shuffle

Java JNI : This operation is only valid in the context of an app container

java - JPA - 按周数获取实体 - Java EE