我有树类。
class MyObject{
public void DoSomething()
{
here I need to call method add from class base.
}
}
class base
{
protected final void add(){}
}
class extended extends base {
private MyObject pObject = new MyObject();
...
{
pObject.DoSomething();
}
}
我可以为扩展类扩展的每个变体创建类,但是只有在已经启动类扩展后才能使用我需要使用的类型。
如何从 MyObject 内部方法调用base.add()
?
答案 0 :(得分:0)
您可以通过以下几种方式实现:
extended
课程中引用您的MyObject
课程。在MyObject
类中实例化extended
变量时,请将extended
的引用传递给它。这样的事情:
class MyObject{
private base baseObj;
public MyObject(base baseObj){
this.baseObj = baseObj;
}
public void DoSomething()
{
//here I need to call method add from class base.
//use baseObj to call the methods
}
}
class base
{
protected final void add(){}
}
class extended extends base {
private MyObject pObject;
...
public extended(){
pObject = new MyObject(this);
}
{
pObject.DoSomething();
}
}
base
class static
中声明方法。这样您就可以调用方法而无需base
类的实例。 这样的事情:
class MyObject{
public void DoSomething()
{
//here I need to call method add from class base.
//call like this
base.add();
}
}
class base
{
protected static final void add(){}
}
class extended extends base {
private MyObject pObject;
...
public extended(){
pObject = new MyObject(this);
}
{
pObject.DoSomething();
}
}
还有一件事:这是偏离主题的,但您可能想了解Java Naming Conventions。让类名以小写开头是你在命名约定中找不到的东西。
答案 1 :(得分:0)
class MyObject{
public void DoSomething(Base base)
{
base.add();
}
}
class extended extends base {
private MyObject pObject = new MyObject();
...
{
pObject.DoSomething(this);
}
}