[英]Can I use a method from a super class in a subclass without overriding it?
我敢肯定这是一个简单的问题,但我不知道答案。 首先,可以做这样的事情吗?
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!”);
}
}
打印的地方是:嗨,那里! 我是一个人! 这只是一个例子,但这可能吗? 如果是这样,我该怎么办? 因此,实际的打印输出为“我是一个人!”。 Person中的sayHi()方法是否必须具有自己的打印输出,显示“嗨,那里!”。 为了这个工作?
如果您有任何疑问,请发表评论,我会尽力而为。 谢谢。
是的,您只需从子类中的方法调用超类中的方法。
请参阅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.
关于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.