简体   繁体   English

我可以在不重写的情况下使用子类中超类的方法吗?

[英]Can I use a method from a super class in a subclass without overriding it?

I'm sure this is a simple question but I don't know the answer. 我敢肯定这是一个简单的问题,但我不知道答案。 First of all, is it possible to do something like this? 首先,可以做这样的事情吗?

public class Entity {


public void sayHi() {
        System.out.println(“Hi there!”);
    }
}

public class Person extends Entity {
    public void sayHi() {
        System.out.println(“I’m a person!”);
    }
}

Where the print out would be: HI there! 打印的地方是:嗨,那里! I'm a person! 我是一个人! This is just an example, but is this possible? 这只是一个例子,但这可能吗? If so how do I do it? 如果是这样,我该怎么办? Because for this, the actual printout would be "I'm a person!". 因此,实际的打印输出为“我是一个人!”。 Would the sayHi() method in Person have to have its own printout that says "Hi There!" Person中的sayHi()方法是否必须具有自己的打印输出,显示“嗨,那里!”。 in order for this to work? 为了这个工作?

If you have any questions leave a comment and I will do my best. 如果您有任何疑问,请发表评论,我会尽力而为。 Thanks. 谢谢。

Yes, you just call the method in the superclass from the method in the subclass. 是的,您只需从子类中的方法调用超类中的方法。

See The Java™ Tutorials - Using the Keyword super . 请参阅Java™教程-使用关键字super

public class Entity {
    public void sayHi() {
        System.out.println("Hi there!");
    }
}
public class Person extends Entity {
    @Override
    public void sayHi() {
        super.sayHi();
        System.out.println("I’m a person!");
    }
}
        public class Entity {
        public void sayHi() {
            System.out.print("Hi there!");

        }
    }
    public class Person extends Entity {
        super.sayHi();
System.out.print("I’m a person!");
    }

I think this may helps you.

Regarding Andreas's anwser, there is a way without add 'super' by java reflection: 关于Andreas的anwser,有一种方法无需通过java反射添加'super':

public class Entity {
    public void sayHi() {
        System.out.println("Hi there!");
    }
}

public class Person extends Entity {
    public void sayHi() {
        System.out.println("I’m a person!");
    }
}

public class Tester {
    public static void main(String[] args) throws Throwable {
        Person x = new Person();
        MethodHandle h1 = MethodHandles.lookup().findSpecial(x.getClass().getSuperclass(), "sayHi",
                MethodType.methodType(void.class),
                x.getClass());

        h1.invoke(x);
        x.sayHi();
    }
}

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

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