Java中的依赖注入和继承
我有以下代码:
public class GrandParent {
public void greet() {
System.out.println("Hello from grandpa.");
}
}
public class Parent extends GrandParent {
public void run() {
greet();
}
}
public class RunMe {
public static void main(String args[]) {
Parent p = new Parent();
p.run();
}
public void greet() {
System.out.println("Hi.");
}
}
我的任务是编写 RunMe 类,并且尽可能不允许我修改 Parent 和 GrandParent 类。我怎样才能以这样的方式实现这一点:当执行到达Parent的run()时,执行RunMe(或者可能在另一个地方)的greet()而不是GrandParent的greet()。
或者这首先有可能吗?
I have the following code:
public class GrandParent {
public void greet() {
System.out.println("Hello from grandpa.");
}
}
public class Parent extends GrandParent {
public void run() {
greet();
}
}
public class RunMe {
public static void main(String args[]) {
Parent p = new Parent();
p.run();
}
public void greet() {
System.out.println("Hi.");
}
}
I am tasked to write the class RunMe and as much as possible, I am not allowed to modify classes Parent and GrandParent. How can I implement this in such a way that when execution reaches run() of Parent, the greet() of RunMe (or it could be in another place) is executed and not the greet() of GrandParent.
Or is this possible in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您要让非扩展父对象调用不同的greet 方法而不更改父对象或祖父母代码,我不明白这怎么可能。
I don't see how this is possible if you are to have a non-extended Parent object call a different greet method without changing Parent or Grandparent code.
您可以在 RunMe 中编写一个实例(非静态)内部类,该内部类扩展 Parent 并覆盖 Parent 实例的 run() ,以便它调用 RunMe 实例的 run() 。您的 main() 方法将创建新子类的实例而不是父类。
You could write an instance (not static) inner class within RunMe that extends Parent and overrides Parent instance's run() such that it makes a call to the RunMe instance's run(). Your main() method would create an instance of the new subclass instead of Parent.
首先,您需要一个 RunMe 实例来调用其 run() 方法,因为这不是静态方法。挂钩
Parent
中发生的情况的一种方法是子类化Parent
:我不知道这是否是您想要的。
First, you need an instance of
RunMe
to invoke itsrun()
method, since that isn't a static method. One way to hook into what's happening inParent
is to subclassParent
:I have no idea if this is what you're after.
试试这个:
try this:
我想你的意思是这样的:
I think you meant this: