OOP Lab 06
OOP Lab 06
Science
Course Code: CSC103
Title: Object-Oriented
Programming
Fall 2024
Lab 06
Objectives:
Introduction to Inheritance
Student Information
Student Name
Student ID
Date
Assessment
Marks Obtained
Remarks
Signature
Lab-06
Inheritance
Objective:
To familiarize students with the concept of Inheritance, types and its advantages.
Coding examples related to inheritance.
Use of super keyword
Example of child class referring Parent class method using super Keyword;
Apparatus:
Hardware requirements:
Dual core CPU based on x64 architecture
Minimum of 1 GB RAM
800 MB of disk space
Software requirements:
Windows 7 SP1 (64 bit)
Java JDK 8 (64 bit JVM)
NetBeans IDE (version 8.1 or above)
Background:
Inheritance and its advantages.
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. Inheritance is one of the most important feature of Object Oriented
Programming.
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
• Reusability: A mechanism which facilitates you to reuse the fields and methods of the
existing class when you create a new class.
.
Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be same for all of the threeclasses. If we create
these classes avoiding inheritance then we have to write all of these functions ineach of the three
classes as shown in below figure:
This increases the chances of error and data redundancy. To avoid this type of situation,
inheritance is used. If we create a class Vehicle and write these three functions in it andinherit
the rest of the classes from the vehicle class, then we can simply avoid the duplication of data
and increase re-usability. Look at the below diagram in which the three classes are inherited
from vehicle class.
.
Code:
// Java Program to illustrate Inheritance (concise)
import java.io.*;
// Base or Super
Classclass
Employee {
int salary = 60000;
}
// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary
+ "\nBenefits : " + E1.benefits);
}
}
Now in this example, we have a base class Animal with a speak method, and two subclasses
Dog and Cat that inherit from Animal and override the speak method with their own
implementations.
Code:
class Animal { void speak() {
System.out.println("The animal speaks.");
}
}
class Dog extends Animal { void speak() {
System.out.println("The dog barks.");
}
}
class Cat extends Animal { void speak() {
System.out.println("The cat meows.");
}
}
.
public class InheritanceExample {
public static void main(String[] args)
{ Animal animal = new Animal();
Dog dog = new Dog();
Cat cat = new Cat();
.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
Call Superclass Constructor: One common use of super is to call the constructor of the
superclass when you're creating an instance of a subclass. This is often done in the constructorof
the subclass to initialize the inherited attributes. For example:
Code:
// Parent class (also known as the superclass) class Vehicle {
String brand; int year;
void start() {
System.out.println("Starting the vehicle");
}
void stop() {
System.out.println("Stopping the vehicle");
}
}
// Child class (also known as the subclass) that inherits from the Vehicle class
class Car extends Vehicle {
int numberOfDoors;
.
Car(String brand, int year, int numberOfDoors) {
super(brand, year); // Call the constructor of the superclass
this.numberOfDoors = numberOfDoors;
}
void accelerate() {
System.out.println("Car is accelerating");
}
}
public class Main {
public static void main(String[] args) {
// Create an instance of the Car class
Car myCar = new Car("Toyota", 2022, 4);
// Access fields and methods from both the parent and child classes
System.out.println("Car brand: " + myCar.brand);
System.out.println("Car year: " + myCar.year);
System.out.println("Number of doors: " + myCar.numberOfDoors);
myCar.start();
myCar.accelerate();
myCar.stop();
}
}
Access Superclass Methods: You can use super to call methods from the superclass if the
subclass overrides them. This is useful when you want to access the overridden method from the
subclass. For example:
class Animal {
void speak() {
System.out.println("The animal speaks.");
}
}
The super keyword is a crucial tool for managing the relationship between classes in inheritance
hierarchies, enabling proper initialization, access, and method invocation.
.
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.
.
Hierarchical Inheritance
In hierarchical inheritance, a single base (parent) class is inherited by multiple derived (child)
classes. This allows each child class to inherit the properties and methods of the parent class
while also having the ability to introduce its own properties and methods.
Code:
class A{
int a = 10;
void show() {
System.out.println("a = "+a);
}
}
class B extends A{
int b = 10;
void showB() {
System.out.println("b = "+b);
}
}
public class C extends A{
public static void main(String[] args) {
C c = new C();
c.show();
B b = new B();
b.show();
}
}
.
Modes of InheritancePublic mode:
If we derive a sub class from a public base class. Then the public member of the base class will
become public in the derived class and protected members of the base class will become
protected in derived class.
Protected mode: If we derive a sub class from a Protected base class. Then both public
member and protected members of the base class will become protected in derived class.
Private mode: If we derive a sub class from a Private base class. Then both public member
and protected members of the base class will become Private in derived class.
Lab exercises:
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.
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.
.
▪ The class Course has the attributes course name, course code, class venue and credit hours, all
are protected members.
▪ Set all these attributes with a parameterized constructor.
▪ Derive a class “Java Course” that has an attribute teacher name.
▪ Make a constructor and invoke the base class’s parameterized constructor.
▪ Set the teacher’s name in the constructor.
▪ The derived class has a function Display that displays all the details of the course and the derived
class.
▪ In the main, display all the details.