Lab 4
Lab 4
Computer Science II
)GEIT 1412(
Lab # 4
Objectives: In this lab, the following topics will be covered
Task 1 :
Inheritance (in Java):
Inheritance is an important object-oriented concept that allows classes to be reused in
order to define similar, but distinct, classes. In this lab we walk through the
development of a class hierarchy and a program that makes use of several classes in
the hierarchy. We begin by looking at an example of inheritance hierarchy
Student
Name
Id
gpa
getName()
getGpa()
getId()
setName()
print()
Undergrad Graduate
year
thesisTitle
setYear()
getYear() setThesisTitle()
print() getThesisTitle()
print()
The class Student is the parent class. Note that all the variables are private and hence
the child classes can only use them through accessor and mutator methods. Also note
the use of overloaded constructors.
public class Student{
private String name;
private int id;
private double gpa;
System.out.println(s1);
System.out.println(s2);
System.out.println(u1);
System.out.println(g1);
Student:
ID: 97000
Name: Sameer
GPA: 3.51
Student:
ID: 98000
Name:
GPA: 3.22
Output Undergraduate Student:
ID: 99000
Name: Shahid
GPA: 2.91
Year: Junior
Graduate Student:
ID: 200000
Name: Mubin
GPA: 3.57
Exercise 1:
Create BookTest class with main method that will do the following:
Task 2
Overriding, Hiding
File Player.java contains a class that holds information about an athlete: name, team,
and uniform number. File ComparePlayers.java contains a skeletal program that uses
the Player class to read in information about two baseball players and determine
whether or not they are the same player.
1. Fill in the missing code in ComparePlayers so that it reads in two players and
prints “Same player” if they are the same, “Different players” if they are
different. Use the equal’s method, which Player inherits from the Object class,
to determine whether two players are the same. Are the results what you
expect?
2. The problem above is that as defined in the Object class, equals does an
address comparison. It says that two objects are the same if they live at the
same memory location, that is, if the variables that hold references to them are
aliases. The two Player objects in this program are not aliases, so even if they
contain exactly the same information they will be “not equal.” To make equals
compare the actual information in the object, you can override it with a
definition specific to the class. It might make sense to say that two players are
“equal” (the same player) if they are on the same team and have the same
uniform number.
o Use this strategy to define an equal’s method for the Player class. Your
method should take a Player object and return true if it is equal to the
current object, false otherwise
o Test your ComparePlayers program using your modified Player class.
It should give the results you would expect.