LAB8
LAB8
INHERITANCE
OBJECTIVE:
To study inheritance and using super to call superclass constructors.
THEORY:
8.1 USING EXISTING CLASSES
Defining a new class based on an existing class is called derivation. The new
class, or derived class, is referred to as a direct subclass of the class from
which it is derived. The original class is called a base class because it forms
the base for the definition of the derived class. The original class is also
referred to as a superclass of the derived class. You can also derive a new
class from a derived class, which in turn was derived from some other derived
class, and so on. This is illustrated in Figure.
8.2 CLASS INHERITANCE
In summary, when you derive a new class from a base class, the process is
additive in terms of what makes up a class definition. The additional members that you define in
the new class establish what makes a derived class object different from a base class object. Any
members that you define in the new class are in addition to those that are already members of the
base class. The inclusion of members of a base class in a derived class so that they are accessible
in that derived class is called class inheritance. An inherited member of a base class is one that is
accessible within the derived class. If a base class member is not accessible in a derived class,
then it is not an inherited member of the derived class, but base class members that are not
inherited still form part of a derived class object.
LAB TASK
1. Develop a registration system for a University. It should consist of three classes namely
Student, Teacher, and Course. For example, a student needs to have a name, roll number,
address and GPA to be eligible for registration. Therefore choose appropriate data types
for encapsulating these properties in a Student objects. Similarly a teacher needs to have
name, address, telephone number, and a degree (or a list of degrees) he/she has received.
Finally courses must have a name, students (5 students) registered for the course, and a
teacher assigned to conduct the course. Create an object of Course with 5 Students and a
Teacher. A call to a method, say printDetails(), of the selected course reference should print
name of the course, details of the teacher assigned to that course, and names and roll
numbers of the students enrolled with the course
CODE:
PERSON CLASS:
STUDENT CLASS:
TEACHER CLASS:
COURSE CLASS:
2. Create a class called computers and two classes MyComputer and YourComputer which
inherits computer class. Define appropriate features of their processor in the classes.
Create another class processor as a composite class of computer. Write a method which
prints the differences between the processors of two computers. Example: single core:
bandwidth = 125GByte/s speed = slow processing = sequentially
CODE:
CLASS PROCESSOR:
CLASS COMPUTER:
CLASS MY COMPUTER:
MAIN CLASS:
OUTPUT: