Search code examples
javaoopextend

Java: how to create and run class structure?


I have to create following class hierarchy.

enter image description here

I started this way:

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

The class called RemoteStudent will look almost the same as the class DailyStudent.

Now I have to create the class StudentTest, where I will test what I just created. In this class I should create the instances (objects) from each class above with using declared constructor (with all arguments). On all created objects I should apply the methods toString() and print().

But here I am facing the problem - I don't know, how to set up the class StudentTest and how to create there all needed instances... and how to use there the method print(), if this method is only int the Student class.

I am total Java newbie, but, are two 2 first methods correct?

Thank you guys for your help and patience.

EDIT: implementation of the StudentTest method:

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

Solution

  • Yes, it looks fine. Is that what you want toString to return though? Also, take a look at abstraction, unless your professor hasn't talked about that yet. Maybe they will introduce this topic. As you can see the toString() method is used in all 3 classes. And you have a class hierarchy.