I'm having difficulty implementing an abstract class structure and was wondering if someone could tell me what i'm doing wrong.
I want to have an abstract parent class Num for which has abstract methods:
where we have two (for now) subclasses:Code:abstract Num add(Num n); abstract Num multiply(Num n)
What I want to be able to do is to create a generic object for which the suitable method is used:Code:public class ComplexNum extends Num public class RealNum extends Num
The two ways that I have tried have failed, namely:Code:Num testNum = new ComplexNum(...) Num otherTestNum = new RealNum(...) testNum.multiply(otherTestNum) // doesn't care what type objs are, handled in subclass
1. Explicitly defining the cases in the abstract class, fails as I want to be able to pass a general Num object i.e. use multiply(Num n), and have the correct method used in the child class.
2. Use type checking in the subclass:Code:abstract Num add(RealNum n); abstract Num add(ComplexNum n); etc
Both seem very anti-OOP, and neither yet work either...Code:public Num add(Num n){ if(n instanceof ComplexNum){ ... } }
Any help greatly appreciated.
Cheers, Hemmer


Reply With Quote

Bookmarks