Java大班组织

时间:2014-11-03 08:53:53

标签: java class oop

我是从Java开始的,如果一个大型组织,就像我想要的那样,我就不会这样做。 我必须在一个类中包含许多参数,我想要访问类似的东西: 例如,我有实现类Person的类Student。但他上课的学生有很多参数,我想把它归类为:

Student John = new Student();

John.physical.setHeight(178);
John.physical.setWeight(70);
John.academic.setQualification(7.5);
John.academic.setSubject(Maths);
John.administrative.setAccountNumber(XXXXX);
John.administrative.setPassport(123456789);
...

我能这样做吗?

3 个答案:

答案 0 :(得分:2)

正如其他人已在评论中指出的那样,您可以使用嵌套类:
例如:

public class Student {

    class Physical {
        int height;
        int weight;

        void setHeight(int height) {
            this.height = height;
        }

        void setWeight(int weight) {
            this.weight = weight;
        }
    }

    class Academic {
        // ...
    }

    class Administrative {
        // ...
    }

    Physical physical = new Physical();
    // ..
}

现在您可以访问:

 John.physical.setHeight(178);

答案 1 :(得分:1)

有几点: 1)您应该将所有嵌套的逻辑单元(如“物理”,“学术”,“管理”)移动到专用实体, 2)您应该为将接收所有初始化参数的每个实体引入适当的构造函数,例如: “物理”的构造函数将是下一个物理(短高度,短权重)(“物理”是实体名称), 3)你应该使用福勒先生和埃文斯先生介绍的“Fluent interface”。 因此,您的代码将以下一种方式重新组织:

Student john = new Student();
john.setPhysical(new Physical(178, 70))
    .setAcademic(new Academic(7.5, Maths))
    .setAdministrative(new Administrative(/*account number*/, /*passport number*/));

<强>更新

每个新课程都应放在“学生”课程之外。他们将负责“学生”课程的特定方面,并从“SOLID”原则满足“S”规则,“学生”课程的实例将拥有该课程的实例。这将使这些类更少耦合,因为,例如,如果应该更改“学术”类而不修改“学生”类,也可以引入几种类型的“学术”实体等。

答案 2 :(得分:0)

您可以通过为类别类型创建单独的类来实现此目的。例如,您可以拥有一个具有高度和权重属性的“PhysicalCharacteristics”类,一个带有accountNumber和passport属性等的“AdministrativeDetails”类。然后,您可以将这些类的实例作为属性放在Student类中。因此,您可以通过从这些类属性中获取属性来访问/编辑属性。例如,要设置高度,您将执行John.getPhysicalCharacteristics()。setHeight(178);

不要忘记在Student构造函数中初始化这些类以避免空引用异常:

例如,如果您的Student类包含“PhysicalCharacteristics physicalCharacteristics;”变量你应该在构造函数中初始化它,如下所示:

public Student(){
   physicalCharacteristics = new PhysicalCharacteristics();
}