I have a class component
abstract class Component{
private componentType m_type;
public Component(componentType type)
{
m_type = type;
}
}
and 2 subclasses
class AmplifierComponent extends Component{
public AmplifierComponent()
{
super(componentType.Amp);
System.out.print(this.m_type);
}
}
class AttenuatorComponent extends Component{
public AttenuatorComponent()
{
super(componentType.Att);
System.out.print(this.m_type);
}
}
my problems are:
1.i can’t instantiate any kind of component because m_type isn’t visible(what that means?)
2.i need to make an array of all the components the user has insert to the chain. i can’t manage to create an array of Component class.
can someone help me with the design?
or with some workarounds?
Thanks in advance
I don’t understand why you need the type member. This looks redundant. You can instead simply do:
and rely on polymorphism for your classes to behave appropriately. Having a type member to identify a hierarchy type is unnecessary when you’ve declared the corresponding classes. If you do have a member variable that is required to be visible in subclasses but not by clients, then you can make it
protectedrather thanprivate.Componentcould be an interface if there’s no functionality/data associated with it.Your array declaration would look like
Polymorphism would mean that you can iterate through this array of components, calling appropriate methods declared on (but not necessarily implemented by) the
Component, and the suitable subclass methods would be called.