【发布时间】:2015-07-17 12:05:21
【问题描述】:
这个问题可能是一个愚蠢的问题,但请帮助我。 我需要重写一个类的行为,但我只会得到它的对象。 以下是代码示例。
我想在所有地方都使用方法 Util.newChildComponent(String id) 本身。
class ParentComponent{
public ParentComponent(String id){}
protected void someBehavior(){}
}
class ChildComponent extends ParentComponent{
public ChildComponent(String id){
super(id);
}
protected void childsBehavior(){}
}
public class Util {
public static ParentComponent newChildComponent(String id)
{
ParentComponent fc = new ChildComponent(id);
// Initialize the object, and performs some common configuration.
// Performs different operations on the generated child object.
// The child class has many members apart from childsBehavior().
return fc;
}
}
// The above classes belongs to a jar, so I cannot edit the code.
// I need to use Util.newChildComponent(String id)
// But I need to override the behavior as mentioned below.
public void f1()
{
// TODO: How to override childsBehavior() method using the object
// I have it in pc? Is it possible?
// Util.newChildComponent(id) method decorates the ChildComponent
// So I need to use the same object and just override childsBehavior() method only.
ParentComponent pc = Util.newChildComponent("childId");
// I need to achieve the result below
/*
ParentComponent pc = new ChildComponent(id){
@Override
protected void childsBehavior(){
super.someBehavior();
// Do the stuff here.
}
}; */
}
提前致谢。
【问题讨论】:
-
所以你想覆盖
childsBehavior,同时使用Util.newChildComponent创建实例? -
而ChildComponent是不能修改的?
-
@milez 所有三个 - ParentComponent、ChildComponent 和 Util
标签: java