Lab Session 7: Relationships Between Classes: Inheritance in Java
Lab Session 7: Relationships Between Classes: Inheritance in Java
BS(SE) 2021
CSS 1042
Department of CS and SE
Important Terminology
Super Class
The class whose features are inherited is known as super class (or a base class or a parent class).
Sub Class
The class that inherits the other class is known as sub class (or a derived class, extended class, or child
class). The subclass can add its own fields and methods in addition to the superclass fields and
methods.
Reusability
Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is
already a class that includes some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the existing class.
Syntax
class derived-class extends base-class
{
//methods and fields
}
Example
In below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class
which extends Bicycle class and class Test is a driver class to run program.
this.speed = speed;
}
// the Bicycle class has three methods
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
// toString() method to print info of Bicycle
public String toString()
{
return("No of gears are "+gear
+"\n"
+ "speed of bicycle is "+speed);
}
}
// derived class
class MountainBike extends Bicycle
{
// the MountainBike subclass adds one more field
public int seatHeight;
Output
No of gears are 3
speed of bicycle is 100
seat height is 25
In above program, when an object of MountainBike class is created, a copy of the all methods and
fields of the superclass acquire memory in this object. That is why, by using the object of the subclass
we can also access the members of a superclass.
If you want to represent any object as a string, toString() method comes into existence. The toString()
method returns the string representation of the object. If you print any object, java compiler internally
invokes the toString() method on the object. So overriding the toString() method, returns the desired
output, it can be the state of an object etc. depends on your implementation.
By overriding the toString() method of the Object class, we can return values of the object, so we
don't need to write much code.
Understanding problem without toString() method.
Let's see the simple code that prints reference.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Ali","Karachi");
Student s2=new Student(102,"Usman","Lahore");
Output
Object Oriented Programming
BS(SE) 2021
CSS 1042
Department of CS and SE
Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I
want to print the values of these objects. Since java compiler internally calls toString() method,
overriding this method will return the specified values. Let's understand it with the example given
below:
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString(){ //overriding the toString() method
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Ali","Karachi");
Student s2=new Student(102,"Usman","Lahore");
Output
101 Ali Karachi
102 Usman Lahore
In practice, inheritance and polymorphism are used together in java to achieve fast performance and
readability of code.
● To access the data members of parent class when both parent and child class have member
with same name
● To explicitly call the no-arg and parameterized constructor of parent class
● To access the method of parent class when child class has overridden that method.
We can use super keyword to access the data member or field of parent class. It is used if parent class
and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color); //prints color of Dog (child) class
System.out.println(super.color); //prints color of Animal (base) class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
Output
Object Oriented Programming
BS(SE) 2021
CSS 1042
Department of CS and SE
black
white
In the above example, Animal and Dog both classes have a common property color. If we print color
property, it will print the color of current class by default. To access the parent property, we need to
use super keyword.
super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void eat(){
System.out.println("eating bread...");
}
void bark(){
System.out.println("barking...");
}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}
}
Output
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method from
Dog class, it will call the eat() method of Dog class by default because priority is given to local. To
call the parent class method, we need to use super keyword.
super is used to invoke parent class constructor
The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
class Animal{
Object Oriented Programming
BS(SE) 2021
CSS 1042
Department of CS and SE
Animal(){
System.out.println("animal is created");
}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}
}
Output
animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there is no super() or
this().
Output
animal is created
dog is created
Output
1 Zaib Ahmad 45000
Exercises
1. Create a class Box having attributes, width, depth and height. Derive a subclass ColorBox from
class Box having an attribute color. Derive a subclass WeightBox from class ColorBox. Write
get/set methods for all attributes in each class. Also write constructors (all) in each class.
2. Write the definition of a class ‘Hotel’ such that it contains the following
Object Oriented Programming
BS(SE) 2021
CSS 1042
Department of CS and SE