[go: up one dir, main page]

0% found this document useful (0 votes)
121 views9 pages

Lab Session 7: Relationships Between Classes: Inheritance in Java

Inheritance allows one class to inherit features from another class. The class whose features are inherited is called the super class or parent class. The class that inherits the features is called the sub class or child class. The sub class can add its own fields and methods in addition to those from the super class. The keyword "extends" is used to inherit from a super class. Overriding methods like toString() allows the sub class to customize the behavior inherited from the super class.

Uploaded by

Parsa Shereen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views9 pages

Lab Session 7: Relationships Between Classes: Inheritance in Java

Inheritance allows one class to inherit features from another class. The class whose features are inherited is called the super class or parent class. The class that inherits the features is called the sub class or child class. The sub class can add its own fields and methods in addition to those from the super class. The keyword "extends" is used to inherit from a super class. Overriding methods like toString() allows the sub class to customize the behavior inherited from the super class.

Uploaded by

Parsa Shereen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Object Oriented Programming

BS(SE) 2021
CSS 1042
Department of CS and SE

Lab Session 7: Relationships between Classes


Inheritance in Java
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in java
by which one class is allow to inherit the features (fields and methods) of another class.

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.

How to use inheritance in Java

The keyword used for inheritance is extends.

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.

//Java program to illustrate the


// concept of inheritance
// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
{
this.gear = gear;
Object Oriented Programming
BS(SE) 2021
CSS 1042
Department of CS and SE

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;

// the MountainBike subclass has one constructor


public MountainBike(int gear,int speed, int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}
// the MountainBike subclass adds one more method
public void setHeight(int newValue)
{
seatHeight = newValue;
}
// overriding toString() method
// of Bicycle to print more info
@Override
public String toString()
{
return (super.toString()+
"\nseat height is "+seatHeight);
}
}
// driver class
public class Test
{
Object Oriented Programming
BS(SE) 2021
CSS 1042
Department of CS and SE

public static void main(String args[])


{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}

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.

Java toString() method

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.

Advantage of Java toString() method

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");

System.out.println(s1); //compiler writes here s1.toString()


System.out.println(s2); //compiler writes here s2.toString()
}
}

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:

Example of Java toString() method


Now let's see the real example of toString() method.

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");

System.out.println(s1); //compiler writes here s1.toString()


System.out.println(s2); //compiler writes here s2.toString()
}
}

Output
101 Ali Karachi
102 Usman Lahore

Java Object Creation of Inherited Class


Illustrative image of the program:
Object Oriented Programming
BS(SE) 2021
CSS 1042
Department of CS and SE

In practice, inheritance and polymorphism are used together in java to achieve fast performance and
readability of code.

Super Keyword in Java


The super keyword refers to the objects of immediate parent class. Before learning super keyword you
must have the knowledge of inheritance in Java so that you can understand the examples given in this
guide.

The use of super keyword

● 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.

super is used to refer immediate parent class instance variable

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().

As we know well that default constructor is provided by compiler automatically if there is no


constructor. But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler implicitly.
class Animal{
Animal(){
System.out.println("animal is created");
}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Object Oriented Programming
BS(SE) 2021
CSS 1042
Department of CS and SE

Dog d=new Dog();


}
}

Output
animal is created
dog is created

super example: real use


Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties of
Person will be inherited to Emp by default. To initialize all the property, we are using parent class
constructor from child class. In such way, we are reusing the parent class constructor.
class Person{
int id;
String name;
Person(int id, String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id, String name, float salary){
super(id, name); //reusing parent constructor
this.salary=salary;
}
void display(){
System.out.println(id+" "+name+" "+salary);
}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"Zaib Ahmad",45000f);
e1.display();
}
}

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

o Three data members: hotel_name, address and tax_number.


o A default empty constructor to create hotel objects with no values assigned to their data
members.
o An overloaded constructor with three parameters to create hotel objects with values
assigned to all three attributes.
o Methods to assign values to the different data members.
o Methods to return the values assigned to the attributes.
Now write down a class ‘GuestHouse’ which inherits from the parent class ‘Hotel’ and
satisfies the following:
o It contains the attributes: permit_no, contact_person and number_of_rooms.
o It contains an overloaded constructor with six parameters which assign values to the data
members inherited and belonging to itself.
o It contains additional set methods to assign values to its own attributes (whose values are
subject to change).
o It contains get methods to return the values assigned to the data members.
3. Implement a class player and two subclasses named batsman and bowler. Each player has a name,
contact address, telephone number and status (either batsman or bowler). The batsman class
maintains the total run obtained by a batsman and the number of one day matches he participated.
Similarly, the bowler class maintains the total wickets taken by a player and the total number of
matches. The parent class contains a method to calculate the average of each player. Implement
the above classes in Java. Provide constructors to initialize the private data. Override the
toString() method in each class to display the class name. Write a program to create an object of
type batsman and bowler and calculate the average run/wickets obtained by a player. Your
program should also call the toString() method to display the class name.

You might also like