Java Inheritance: Creating Subclasses and Reusing Code, Lab Reports of Computer Science

An exercise on java inheritance, where you will create a new class (subclass) that extends a previously defined class (superclass) and inherits its data and methods. The example uses classes person and employee, and you will create a new class student that extends person. Pay attention to the constructor calls, method overriding, and access modifiers.

Typology: Lab Reports

Pre 2010

Uploaded on 04/12/2010

koofers-user-6x2
koofers-user-6x2 🇺🇸

10 documents

1 / 2

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Part 1: Inheritance
In this exercise you will:
1. Investigate how classes inherit data and methods from their parent classes.
pf2

Partial preview of the text

Download Java Inheritance: Creating Subclasses and Reusing Code and more Lab Reports Computer Science in PDF only on Docsity!

Part 1: Inheritance

In this exercise you will:

  1. Investigate how classes inherit data and methods from their parent classes.

Inheritance allows us to create a new class (called the subclass or child class) that extends a previously defined class (called the super, parent, or base class). This new class inherits all of the data and methods of the super class, and then adds additional data or methods. Inheritance allows us to reuse Java code that has been previously developed thus decreasing the costs needed to develop a new application.

For example: class Person contains data and methods for information common to all persons (name, date of birth and address). Class Employee extends class Person and therefore inherits all of the data and methods of the Person class. Class Employee then adds data and methods for the employee’s department, title and salary.

Closely examine files Person.java and Employee.java. Pay particular attention to the following:

  • Class Employee extends class Person
  • The Employee constructor calls the Person constructor by using the keyword super. This is how the Employee constructor can pass information to the Person constructor, which is then executed.
  • The toString method in the Employee class calls the toString method of the Person class with super.toString()
  • In the Person class instance variables name, address, and dateOfBirth are declared as protected instead of private. This allows any subclass (such as Employee) to have access to these variables if needed.

Experiment 7.

Step 1. Compile and run test program InheritanceTest.java and see how the Employee objects are able to execute methods in the Person class.

Step 2. Now create class Student which will extend Person and contain major, hours, and GPA data.

Step 3. Uncomment the code in InheritanceTest.java and compile and execute it to test your solution.