Lab 10 Java - 2k20
Lab 10 Java - 2k20
Lab Manual
OOP
3rdSemester Lab-10: Inheritance in Java
Laboratory 10:
Statement Purpose: At the end of this lab, the students should be able to:
• Implement Inheritance Concepts
• Use Super keyword
• Create and use Abstract class and abstract methods
• Implement Polymorphism
Inheritance:
Inheritance is one of the cornerstones of OOP because it allows the creation of hierarchical
classifications. Using inheritance, a general class can be created that contains or defines traits common
to a set of related items. This class can then be inherited by other, more specific classes, each adding
those things that are unique to it. A class that is inherited is called a superclass. The class that does the
inheritance is called a subclass. A subclass inherits all the instance variables and methods defined by
the superclass and add its own, unique elements.
Types of inheritance:
• Single inheritance: refers to a child and parent class relationship where a class extends another
class.
• Multilevel inheritance: refers to a child and parent class relationship where a class extends the
child class. For example, class C extends class B and class B extends class A.
• Hierarchical inheritance: refers to a child and parent class relationship where more than one
classes extends the same class. For example, classes B, C & D extends the same class A.
Multiple Inheritance: refers to the concept of one class extending more than one classes, which means
a child class has two parent classes. For example, class C extends both classes A and B. Java does not
support multiple inheritance.
A B
Multiple Inheritance
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.
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;
//derived class
class MountainBike extends Bicycle
{
// the MountainBike subclass adds one more field
public int seatHeight;
this.gear=gear;
this.speed=speed;
seatHeight = startHeight;
}
//driver class
public class example1
{
public static void main(String args[])
{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}
Output:
Using Super:
Example:
In above code, in derived class constructor, the two statements setting gear and speed can be
replaced and super keyword is used to call the superclass constructor which sets these attributes
with values. Output will be same as above.
// initialize gear, speed and seatheight using super()
public MountainBike(int gear,int speed,int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
//this.gear=gear;
//this.speed=speed;
seatHeight = startHeight;
}
• The second is used to access a member of the superclass that has been hidden by a member of
a subclass.
super.member
Here,member can be either a method or an instance variable
// overriding toString() method of Bicycle to print more info
public String toString()
{
return (super.toString()+
"\nseat height is "+seatHeight);
}
Example:
//A complete example demonstrating forms of super keyword
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;
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;
{
return (super.toString()+ "\nseat height is "+seatHeight);
}
}
//driver class
public class example1
{
public static void main(String args[])
{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}
Output:
Note:
1. When a subclass calls super(), it is calling the constructor of its immediate superclass. Thus,
super() always refers to the superclass immediately above the calling class.
2. Super() must always be the first statement executed inside a subclass constructor.
Method Overriding:
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within a subclass, it will always refer
to the version of that method defined by the subclass. The version of the method defined by
the superclass will be hidden.
Note: Do not confuse the term overriding with the term overloading, overriding means
inheriting a method from the super class and altering its functionality, while overloading means
having constructors and methods with the same name but with different signatures.
Example:
//Dog.java
//A class that holds a dog's name and can make it speak.
public class Dog
{
protected String name;
// Constructor -- store name
public Dog(String name)
{
this.name = name;
}
// Returns the dog's name
public String getName()
{
return name;
}
// Returns a string with the dog's comments
public String speak()
{
return "Woof";
}
}
//Labrador.java
//A class derived from Dog that holds information about a labrador retriever.
//Overrides Dog speak method and includes information about avg weight for this
//breed.
public class Labrador extends Dog
{
public String color; //black, yellow, or chocolate?
private static int breedWeight = 75;
public Labrador(String name, String color)
{
super(name);
this.color = color;
}
// Big bark -- overrides speak method in Dog
public String speak()
{
return "WOOF";
}
// Returns weight
public static int avgBreedWeight()
{
return breedWeight;
}
}
//Yorkshire.java
//A class derived from Dog that holds information about
//a Yorkshire terrier. Overrides Dog speak method.
public class Yorkshire extends Dog
{
public Yorkshire(String name)
{
super(name);
}
// Small bark -- overrides speak method in Dog
public String speak()
{
return "woof";
}
}
//DogTest.java
//A simple test class that creates a Dog and makes it speak.
public class DogTest {
public static void main(String[] args) {
Dog dog = new Dog("Spike");
Labrador dog1 = new Labrador("Spike2", "white");
Yorkshire dog3=new Yorkshire("Spike3") ;
System.out.println(dog.getName() + " says " + dog.speak());
Abstraction:
In Object-oriented programming, abstraction is a process of hiding the implementation details
from the user, only the functionality will be provided to the user. In other words, the user will
have the information on what the object does instead of how it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.
Abstract Class:
A class which contains the abstract keyword in its declaration is known as abstract class.
1. Abstract classes may or may not contain abstract methods, i.e., methods without body
( public void get(); )
2. But, if a class has at least one abstract method, then the class must be declared abstract.
3. If a class is declared abstract, it cannot be instantiated.
4. If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.
Abstract Methods
If you want a class to contain a particular method but you want the actual implementation of
that method to be determined by child classes, you can declare the method in the parent class
as an abstract.
• abstract keyword is used to declare the method as abstract.
• You must place the abstract keyword before the method name in the method
declaration.
• An abstract method contains a method signature, but no method body.
• Instead of curly braces, an abstract method will have a semicolon (;) at the end.
• It can never be static and final. Private method cannot be abstract.
Example:
Following is an example of the abstract method.
public abstract class Employee
{
private String name;
private String address;
private int number;
public abstract double computePay();
//Remainder of class definition
}
Output:
Polymorphism:
Polymorphism is the ability to create a variable, a function, or an object that has more than
one form. Method overriding is a feature which you get when you implement inheritance in
your program.
In java language, polymorphism is essentially considered into two versions.
A simple example can be from real world e.g. Animal. An application can have Animal class,
and its specialized sub classes like Cat and Dog. These subclasses will override the default
behavior provided by Animal class plus some of its own specific behavior.
class Animal {
public void makeNoise()
{
System.out.println("Some sound");
}
}
class Dog extends Animal{
public void makeNoise()
{
System.out.println("Bark");
}
}
class Cat extends Animal{
public void makeNoise()
{
System.out.println("Meawoo");
} }
Now which makeNoise() method will be called, depends on type of actual instance created on
runtime e.g.
public class Poly_example {
public static void main(String[] args) {
Animal a1 = new Cat();
a1.makeNoise(); //Prints Meowoo
Animal a2 = new Dog();
a2.makeNoise(); //Prints Bark
}
}
Output:
Meawoo
Bark
Java uses a technique for method invocation called "dynamic dispatch". If I have
class A {
public void draw() {
System.out.println("draw in A class"); }
public void spin() {
System.out.println("spin in A class"); }
}
class B extends A {
public void draw() {
System.out.println("draw in B class");
}
public void bad() {
System.out.println("bad in B class");
}
}
Output:
Then we see that B inherits spin from A. However, when we try to manipulate the object as
if it were a type A, we still get B's behavior for draw. The draw behavior is polymorphic.
It is the type of the reference variable-not the type of the object that it refers to – that
determines what members can be accessed. That is, when a reference to a subclass is assigned
to a superclass reference variable, you will have access only to those parts of the object defined
by the superclass.
}
int sum()//define method
{
return no1 + no2;//return Addition
}
}
class Subtraction extends Calculator//extends with Superclass
{
Subtraction (int n1, int n2)
{
no1 = n1; no2 = n2;
}
int sum()//define method
{
return no1 - no2; //return Subtraction
}
}
class Multiplication extends Calculator //extends with Superclass
{
Multiplication (int n1, int n2)
{
no1 = n1; no2 = n2;
}
int sum() //define method
{
return no1 * no2; //return Multiplication
}
}
Output:
Multi-level Inheritance:
Suppose, we have a form (class A is the parent of class B and class B is the parent of class
C), then features of A are available for B, and features of B (including that of A) are available
for C. So, class C get features of both A and B.
In this case, class B is the parent to C and child to A. such classes are generally known as
intermediate classes. When an object of class C is created, constructors of all the three classes
will be executed.
Even though the control goes to the constructor of C first, the actual sequence of execution will
be the constructor of A first, the constructor of B next and constructor of C at last.
class Person
{
Person()
{
System.out.println("Person constructor");
}
void nationality()
{
System.out.println("Pakistani");
}
void place()
{
System.out.println("Islamabad");
}
}
class Emp extends Person
{
Emp()
{
System.out.println("Employee constructor");
}
void organization()
{
System.out.println("IBM");
}
void place()
{
System.out.println("New York");
}
}
class Manager extends Emp
{
Manager()
{
System.out.println("Manager constructor");
}
void subordinates()
{
System.out.println(12);
}
void place()
{
System.out.println("London");
}
}
public class multi {
public static void main(String arg[])
{
Manager m=new Manager();
m.nationality();
m.organization();
m.subordinates();
m.place();
}
}
Output:
Hierarchical Inheritance:
class A
{
//code of class A
}
class B extends A
{
//code of class B
}
class C extends A
{
//code of class C
}
Lab Tasks
Task 1: Marks: 4
Make an abstract class named Shape with two abstract methods area and perimeter. Implement
a subclass “EquilateralTriangle” having a double variable side denoting the three sides of the
equilateral triangle [Note that since all the 3 sides are equal, the constructor will have only one
parameter]. The area and perimeter of the equilateral triangle are given as follows:
Area = ¼* 3 *(side)2
Perimeter = 3*side
Test your class using the main class TestShapes.
Task 2: Marks: 6
Make a class with any name (Lab_10). Declare two variables i and j of type int in it. In constructor,
initialize these variable with values specified in parameters. Make a method named calculate in this
class of double return type. In this method, perform the addition of i and j and display the result. Make
a second class (SubC2) which inherits from first class (Lab_10). In this class’s constructor, pass two
values as parameters but initialize the fields using superclass’s constructor (using super). Override the
method calculate() defined in superclass. In overridden method, calculate the difference of i and j and
print the result. Then create a class in the same way for multiplication and division and override the
method for multiplication and division respectively. Make another class(Add3V) which extends
Lab_10. In this class, declare a variable c of int type. In constructor of Add3V, call superclass
constructor and then set value of c also. In calculate method, first call calculate method of superclass.
Then print the value of c. Then calculate the sum of three variables i, j and c as sum is returned from
calculate() method of superclass. In main class(Calculatedemo), Make objects of the above classes and
call method calculate.
***************