Inheritance, Specialization, and Generalization
Objective
- Apply inheritance in application development.
- Write classes with overridden methods.
Exercise 1*
-
Create a new project, a package named
model
, and a package namedtest
. -
In the
model
package, create a class calledPerson
that has two data members:id
:int
andname
:String
. Add corresponding setter/getter methods. -
Create a new class named
Employee
that inherits (specializes) classPerson
and has one additional data member:noOfChildren
. -
Add setter/getter method for this new field.
According to this the superclass (parent) is
_______
and the subclass (child) is_______
. -
In the
model
package, create a new classAppTest
with amain()
method. In themain()
method, create an object of typeEmployee
. -
Using setter methods, set the object’s data as follows:
id
to123
,name
to"Khaled"
, andnoOfChildren
to2
.Note that the methods
setId()
andsetName()
are not defined in theEmployee
class but inherited fromPerson
. -
Output the name, ID, and number of children for the above employee.
-
In class
Employee
, add a constructor that receives one parameter (int
) to initialize the fieldnoOfChildren
. This results in an error. Why?To solve this, add a default constructor in the
Employee
class. -
Add a constructor to
Person
that receives two parameters to initializeid
andname
. Add an output statement in this constructor to print"Person constructor called"
. This results in an error. Why?To solve this, add a default constructor in the
Person
class. -
Add a constructor in class
Employee
that receives three parameters:int
,String
, andint
to initialize all data members.-
Can you access the
id
andname
fields directly in this constructor? -
If not, then how to solve this issue?
One solution is to use the setters of these fields. An alternative way is to explicitly call the constructor of the superclass. How to do that?
-
Use the keyword
super
to call the superclass’s constructor to initialize the data, in a similar fashion to the use ofthis()
to call an overloaded constructor. Also add output statements in this constructor to print"Employee constructor called"
. -
Can you make the superclass constructor call as the last statement?
-
-
In the
main()
method, create a new object as follows:Employee emp = new Employee(124, "Ameen", 1);
Run the program. What is the output? What do you conclude regarding the order of constructor calls?
-
Change the access modifiers of
id
andname
in classPerson
toprotected
instead ofprivate
. Now try to access them directly in theEmployee
class. Are they accessible?In the
main()
method, try to access theid
andname
of objectemp
. Are they accessible?Notice that
AppTest
is not a member of the inheritance hierarchy, but it has access to the protected members. Explain and elaborate.Refer to Controlling Access to Members of a Class (opens in a new tab) to learn more about access modifiers:
Modifier Class Package Subclass World public
protected
private
-
Move the
AppTest
class to thetest
package that you created earlier. Explain the errors you get when you try to run your application and propose ways to fix them. -
Create the
public
methodtoString()
in classPerson
that returns the person’s id and name as comma-separated values (CSV
). Output the details ofemp
usingtoString()
. -
In class
Employee
, create a public methodtoString()
to return all the employee’s data: ID, name, and number of children as comma-separated values.- Having two methods with the same name and signature, one in the superclass and one in the subclass is called
_______
. - How to call the superclass method
toString()
from the subclass?
- Having two methods with the same name and signature, one in the superclass and one in the subclass is called
-
Modify the access modifier of
toString()
in classEmployee
toprotected
instead ofpublic
. What do you conclude? -
Now restore
toString()
’s access modifier topublic
. Also make theid
andname
fields private and fix all references made to them. Also remove the output statements from the constructors of thePerson
andEmployee
classes, as they are no longer needed.
Exercise 2
-
Add the following three classes to your project:
Vehicle.javapackage model; public class Vehicle { private int wheels; private double weight; public Vehicle() {} public Vehicle(int wheels, double weight) { this.wheels = wheels; this.weight = weight; } public int getWheels() { return wheels; } public void setWheels(int wheels) { this.wheels = wheels; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } @Override public String toString() { String dashes = ""; String className = getClass().getSimpleName(); for (int i = 0; i < className.length(); i++) { dashes += "-"; } return className + "\n" + dashes + "\n" + "Wheels: " + wheels + "\n" + "Weight: " + weight + "\n"; } }
Car.javapackage model; public class Car extends Vehicle { private int passengers; public Car() {} public Car(int wheels, double weight, int passengers) { super(wheels, weight); this.passengers = passengers; } public int getPassengers() { return passengers; } public void setPassengers(int passengers) { this.passengers = passengers; } @Override public String toString() { return super.toString() + "Passengers: " + passengers + "\n"; } }
VehicleTest.javapackage test; import model.*; public class VehicleTest { public static void main(String[] args) { Vehicle bicycle = new Vehicle(2, 20.0); Car sedan = new Car(); Car toyota = new Car(4, 2000.0, 5); sedan.setWheels(4); sedan.setPassengers(4); sedan.setWeight(1500.0); System.out.println(bicycle); System.out.println(sedan); System.out.println(toyota); } }
-
Run the
VehicleTest
class’smain()
method. -
Add to the
Vehicle
class the public methodgetAsCSV()
that returns the field values as comma-separated values. Let the last value in the comma-separated string be the name of the class preceded with a comma.Hint: Use the
getClass().getSimpleName()
from theObject
class. Override this method in theCar
class. Display thebicycle
,sedan
, andtoyota
objects as comma-separated values. -
Add a class called
Truck
to themodel
package that inherits from theVehicle
class.Truck
objects have the fields:- number of wheels (
wheels
) - truck weight (
weight
) - load capacity (
capacity
)
and the methods:
- getters and setters
- no-argument constructor
- parametrized constructor
getWheelLoad()
: returns the wheel load which is equal to(weight + capacity) / wheels
.toString()
: overrides the superclass method by adding the truck details and the wheel load to the string generated by the superclass. Let the returned string be properly formatted.getAsCSV()
: overrides the superclass method by returning all the values of a truck object as comma-separated values without including the wheel load.
- number of wheels (
-
Update the
main()
method in theVehicleTest
to perform the following:- Create a
Truck
object named"volvo"
with the data:- Number of wheels: 12
- Truck weight: 4,000 kg
- Load capacity: 12,000 kg
- Display the
"volvo"
data using bothtoString()
andgetAsCSV()
methods.
- Create a
Exercise 3
-
In the
test
package, create a new class calledPersonTest
which contains amain()
method that tests thePerson
class by creating aList
ofPerson
instances, where the elements are initialized using the following data:ID Name 1318 Jane Doe 2571 John Doe 5376 Sara Smith -
Write statements to output the contents of the 3 instances then save your file and run it.
Exercise 4+
- In the
model
package, create a class calledStudent
that inherits from thePerson
class. A student has three data members:id
:int
,name
:String
, andmajor
:String
. - Add setter/getter methods for the additional field. Also add a
toString()
method that returns all the student details as a string. - In the
AppTest
class, create twoStudent
instances. - Display the details of the two students you have just created.