Sie sind auf Seite 1von 2

Computer Programming Tutorial Sheet Inheritance

If you didnt do it last week, make sure you demonstrate Interim Deliverable C to
your lab tutor.
In the lecture we looked at inheritance in Java. If class A extends class B then A re-uses
the instance variables and methods of B.

DURING THE LAB / UNSUPERVISED LEARNING

Core Exercise (for everyone)


Using the UML below as a guide, extend Person.java (from the download) twice
first extend Person to make a Student class and then extend Student to make an
Undergraduate classes.
Keep the variable names from the UML as inputs and follow the specification below
to construct the methods.
Use out.println() for the register method to display the data.
Person
#name:String
#age:int
+Person()
+Person(nameInput:String,ageInput:int)
+setName(newName:String):void
+setAge(newAge:int):void
+register():void
Student
#avMark:int
+Student()
+Student(nameInput:String,
ageInput:int,markInput:int)
+setMark(markIn:int): void
+study(hours:int):void
+register():void
Undergraduate
#prog:String
#year:int
+Undergraduate ()
+Undergraduate(nameInput:String,ageInput:int,markInput:int,progInput:String,yearInput:int)
+setProg(progIn:String):void
+setYear(yearIn:int):void
+study(hours:int):void
+changeYear():void
+getYear():int
+register():void

Computer Programming Tutorial Sheet Inheritance


Specification
Student should extend Person by having an average mark, avMark.
The study() method of the Student class is passed the number of hours studied per
day (up to 6) as an argument and uses this to change avMark with the formula:
avMark = avMark + (hours*2)
The register method should override the register method in Person to give the
avMark as well as their name and age.
Undergraduate should extend Student by having a programme of study, prog, and an
academic year, year, as attributes.
The study() method of Undergraduate should use a different formula from Student (as
the undergraduate is distracted from their studies a bit) so override study() with the
formula:
avMark = avMark+(hours*2) 5
The changeYear() method should increase the year they are in by 1. You can find out
what year they are currently in using getYear().
The register() method should override the Student method to give the prog and year
as well.
After writing each new class, create a test harnesses (TestStudent and
TestUndergraduate) to exercise all parts of your 2 classes (if you are stuck on this
have a look at TestPerson below).
The test harness should create instances of the class with both constructors and test all
methods, including those inherited.

IMPORTANT NOTE
You do not need inheritance for your coursework (unless it is very comprehensive).

Das könnte Ihnen auch gefallen