Java

OOP GUIDE / WORK

 

PERSON SUPERCLASS AND STUDENT & TEACHER SUBCLASSES

 

Topics

  • Extending a superclass
  • Creating a subclass
  • Calling a superconstructor
  • Testing subclass objects for superclass instance variables and methods

 

 

TASK – PART 1 – CONSIDER THE PERSON CLASS

 

Copy the following class to your IDE.

 

 

public class Person

{

     public String name;

     public int yob;

    

     public Person(String n, int yob)

     {

           name = n;

           this.yob = yob;

     }

    

     public String toString()

     {

           return name + " (" + yob + ")";

     }

    

     public int getAge()

     {

           return 2021 - yob;   //change 2021 to current year

     }

}

 

 

 

TASK – PART 2 – TEST THE PERSON CLASS

 

Inside a Tester class, insert a main method and do the following:

 

  • Create a Person object that represents you. 

  • Use its toString() method to output its state to screen.

  • Output the object’s age to screen.

 

 

TASK – PART 3 – THE STUDENT CLASS

 

Make a new class named Student.  Make it extend the Person class.

 

Here are the specs for the Student class:

 

INSTANCE VARIABLES

  • school
  • studentNumber

 

CONSTRUCTOR

 

  • A constructor that gets four parameters, one for each instance variable.  Don’t forget to call the superconstructor.

 

INSTANCE METHOD(S)

 

  • A toString() method that outputs a string representation of the student.

 

 

TASK – PART 4 – TEST THE STUDENT CLASS

 

Inside the same tester class as in Part 2, do the following:

 

  • Create a Student object with the following values
    • Name: Jim Bo
    • Year of birth: 2007
    • School: Lockerby
    • Student number: 123456789 

  • Use its toString() method to output its state to screen.

  • Output the object’s age to screen.  Notice that this method is inherited from the Person class!

 

 

TASK – PART 5 – THE TEACHER CLASS

 

Make a new class named Teacher.  Make it extend the Person class.

 

Here are the specs for the Teacher class:

 

INSTANCE VARIABLES

  • school
  • areaOfSpecialty

 

CONSTRUCTOR

 

  • A constructor that gets four parameters, one for each instance variable.  Don’t forget to call the superconstructor.

 

INSTANCE METHOD(S)

 

  • A toString() method that outputs a string representation of the teacher.  However, you should make use of the Person’s toString method by using super.toString() to build part of your string.

 

 

TASK – PART 6 – TEST THE TEACHER CLASS

 

Inside the same tester class as in Part 2, do the following:

 

  • Create a Teacher object with the following values
    • Name: Mr. D.
    • Year of birth: 1968
    • School: Xavier Academy
    • areaOfSpecialty: Social Studies

  • Use its toString() method to output its state to screen.

  • Output the object’s age to screen.  Notice that this method is inherited from the Person class!