私は次のクラスを持っています
class Person {
private String name;
void getName(){...}}
class Student extends Person{
String class;
void getClass(){...}
}
class Teacher extends Person{
String experience;
void getExperience(){...}
}
これは私の実際のスキーマの単純化されたバージョンです。最初は、作成する必要のある人物のタイプがわからないため、これらのオブジェクトの作成を処理する関数は、一般的なPerson
オブジェクトをパラメーターとして受け取ります。
void calculate(Person p){...}
次に、この親クラスオブジェクトを使用して子クラスのメソッドにアクセスします。また、親クラスのメソッドに時々アクセスする必要があるため、抽象化できません。
上記の例では単純化しすぎたと思いますので、これが実際の構造です。
class Question {
// private attributes
:
private QuestionOption option;
// getters and setters for private attributes
:
public QuestionOption getOption(){...}
}
class QuestionOption{
....
}
class ChoiceQuestionOption extends QuestionOption{
private boolean allowMultiple;
public boolean getMultiple(){...}
}
class Survey{
void renderSurvey(Question q) {
/*
Depending on the type of question (choice, dropdwn or other, I have to render
the question on the UI. The class that calls this doesnt have compile time
knowledge of the type of question that is going to be rendered. Each question
type has its own rendering function. If this is for choice , I need to access
its functions using q.
*/
if(q.getOption().getMultiple())
{...}
}
}
ifステートメントは「QuestionOptionのgetMultipleが見つかりません」と言っています。OuestionOptionには、子間で一般的ではないさまざまなタイプのメソッドを持つ子クラスがさらに多くあります(getMultipleは子間で一般的ではありません)