Reputation: 5055
I have several classes that extend others. They both have a common method result
. If I have an instance of foobarbaz
, is it possible to call its parent's/grandparent's result
method?
public class Foo {
protected int resultA;
public void calc(){ resultA=...}
public void result(){ return resultA; }
}
public class Foobar extends Foo{
protected int resultA;
public void calc(){
super.calc();
resultB=...;
}
public void result(){ return resultB; }
}
public class Foobarbaz extends Foobar{
protected int resultA;
public void calc(){
super.calc();
resultC=...;
}
public void result(){ return resultC; }
}
The problem I'm trying to solve is that each class does some extra calculation, besides the one of its parent. If user wants results from all 3 objects, the CalculationManager knows only Foobarbaz needs to be inited and calculated. Then it returns an reference to Foobarbaz to whoever is asking for Foo, because Foobarbaz will have a result for Foo as well.
Something like:
CalculationManager.add(Foo,Foobar,Foobarbaz);
//The following 3 calls return the same reference to a Foobarbaz object
Foo res1=CalculationManager.get(Foo);
Foobar res2=CalculationManager.get(Foobar);
Foobarbaz res3=CalculationManager.get(Foobarbaz);
CalculationManager.doCalc();
//Iterate over each object to get result with the same method .result()
res1.result(); //---> resultA
res2.result(); //---> resultB
res3.result(); //---> resultC
Upvotes: 4
Views: 7628
Reputation: 2046
Design Principle: Favor composition over inheritance
Get a copy of the Head First Design Patterns book and read about Strategy, Template and maybe also Factory patterns. Other patterns discussed in there will certainly come in handy elsewhere in this project or projects to come.
Possible scenario:
At the point where you worry about the different Calculator implementations have common code you can make use of the Template pattern or have them extend from a BaseCalculator etc.
This should keep you busy for some time but if you do it right and get the hang of it you'll find that using patterns like this helps you in many programming situations. Hence the name patterns, I guess ;-)
Upvotes: 1
Reputation: 103145
This is not really possible. You will have to instantiate an object of the parent class in order to call its print method.
e.g.
FooBar f = new FooBar();
f.print(); //foobar
Only from within the sub class can you use super keyword to access the super class' method.
Upvotes: 1
Reputation: 24336
you would need something like this in each class:
Foo:
printParent()
{
super.printParent();
}
FooBar:
printParent()
{
super.printParent();
}
FooBarBaz:
printParent()
{
print(); // this is the top most class
//Incredibly fragile!
}
Upvotes: 2