0

次のクラス階層を作成する必要があります。

ここに画像の説明を入力してください

私はこのように始めました:

public class Student {
  private String name;
  private int credits;
  public Student(String name, int credits) {
    this.name = name;
    this.credits = credits;
  }

  public String getName(){
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
  // ...the same for "credits"...

  public String toString(){
    return "name: "+this.name+", credits: "+this.credits;
  }

  public void print(){
    System.out.print(this.toString);
  }
}

public class DailyStudent extends Student {
  private int scholarship;
  public DenniStudent(int scholarship) {
    this.scholarship = scholarship;
  }

  public int getScholarship(){
    return scholarship;
  }
  public void setScholarship(int scholarship) {
    this.scholarship = scholarship;
  }
  public String toString(){
    return "Scholarship: "+scholarship;
  }
}

RemoteStudentというクラスは、DailyStudentクラスとほぼ同じように見えます。

次に、クラスStudentTestを作成する必要があります。ここで、作成したものをテストします。このクラスでは、宣言されたコンストラクター(すべての引数を含む)を使用して、上記の各クラスからインスタンス(オブジェクト)を作成する必要があります。作成されたすべてのオブジェクトに、メソッドtoString()およびprint()を適用する必要があります。

しかし、ここで私は問題に直面しています-クラスStudentTestを設定する方法と、そこに必要なすべてのインスタンスを作成する方法...そして、このメソッドがintのみである場合は、メソッドprint()を使用する方法がわかりません学生クラス。

私は完全なJava初心者ですが、最初の2つの方法は正しいですか?

皆さんの助けと忍耐に感謝します。

編集:StudentTestメソッドの実装:

public class StudentTest {
  public static void main(String[] args) {
    DailyStudent daily = new DailyStudent(1000);
    daily.print(); // this is what I mean
  }
}
4

2 に答える 2

1

はい、問題ないようです。toStringそれはあなたが返したいものですか?また、教授がまだそれについて話していない場合を除き、抽象化について調べてください。多分彼らはこのトピックを紹介します。ご覧のとおり、このtoString()メソッドは 3 つのクラスすべてで使用されています。そして、クラス階層があります。

于 2013-01-22T17:14:38.673 に答える
0

一つ一つ問題を解いていきましょう。

  1. インスタンスを作成するには、Factory パターンを使用します。StudentFactory必要なすべての引数を持つメソッドを持つクラスを作成createStudent()し、これらの引数に従ってリモートまたは毎日の学生を作成します。次のように使用します。

    Student Student = StudentFactory.create(......);

これからは、Student を使用できるようになり、工場外の誰もそれがどの Student であるかを知ることはありません。

  1. print今すぐメソッドを使用できます: student.print(). 遠隔地の学生と毎日の学生の両方に機能します。

  2. テストで factory を使用します。JUnit ベースのテストの場合は、アノテーション@RunWith(Parametrized.class)を使用して、毎日の生徒とリモートの生徒の両方に対して実行されるテスト ケースを 1 つだけ作成できます。

    @RunWith(Parameterized.class) public class StudentTest { プライベート Student Student;

    public StudentTest(Student student) {
        this.student = student;
    }
    
    @Parameter
    public static Collection<Student> createStudent() {
        return  Arrays.asList(
                    StudentFactory.create(....),    // create remote student
                    StudentFactory.create(....));   // create daily student
    }
    // write your tests here
    

    }

このテスト ケースは、createStudent()メソッドで作成された両方の生徒に対して実行されます。

于 2013-01-22T17:26:29.717 に答える