vintox
vintox

Reputation: 55

abstract class arrays and oop design - Java

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

Upvotes: 1

Views: 1089

Answers (3)

Noam Tsalisher
Noam Tsalisher

Reputation: 1

abstract class Component {
    private componentType m_type;

    public Component(componentType type)
    {
        m_type = type;
    }

    public componentType getType()
    {
        return this.m_type;
    }
}

class AmplifierComponent extends Component{
    public AmplifierComponent()
    {
        super(componentType.Amp);
        System.out.print(super.getType());
    }
}

class AttenuatorComponent extends Component{
    public AttenuatorComponent()
    {
        super(componentType.Att);
        System.out.print(super.getType());
    }
}

That way you can read m_type, but cannot change it. You could also make the getType() command protected, so it is only reachable through the classes which inherit it.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272367

I don't understand why you need the type member. This looks redundant. You can instead simply do:

abstract class Component{
}

class AttenuatorComponent extends Component{
    public AttenuatorComponent() {
       // calls the default super constructor
    }
}

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 protected rather than private.

Component could be an interface if there's no functionality/data associated with it.

Your array declaration would look like

Component[] components = new Component[20];
components[0] = new AttenuatorComponent();

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.

Upvotes: 6

palako
palako

Reputation: 3470

Set m_type to protected to be able to see it from child classes.

Upvotes: 0

Related Questions