1

我有一个类组件

abstract class Component{
    private componentType m_type;

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

和 2 个子类

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);
    }
}

我的问题是: 1.我无法实例化任何类型的组件,因为 m_type 不可见(这意味着什么?) 2.我
需要创建一个用户插入到链中的所有组件的数组。我无法创建组件类的数组。

有人可以帮我设计吗?
或有一些解决方法?

提前致谢

4

3 回答 3

6

我不明白你为什么需要类型成员。这看起来是多余的。您可以改为简单地执行以下操作:

abstract class Component{
}

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

并依靠多态性让你的类表现得恰到好处。当您声明了相应的类时,不需要使用类型成员来标识层次结构类型。如果您确实有一个成员变量需要在子类中可见但对客户端不可见,那么您可以制作它protected而不是private.

Component如果没有与之关联的功能/数据,则可能是一个接口。

你的数组声明看起来像

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

多态意味着您可以遍历这个组件数组,调用在 上声明(但不一定由其实现)的Component适当方法,并且将调用适当的子类方法。

于 2012-12-14T10:59:10.590 回答
0

将 m_type 设置为 protected 以便能够从子类中看到它。

于 2012-12-14T11:00:25.147 回答
0
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.

于 2014-02-05T23:03:35.210 回答