Inheritance and Polymorphism

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

INHERITANCE AND POLYMORPHISM

Inheritance the technique by virtue of which a class acquires the properties and
features (Data Members and Member Methods) of another class.
A class that gets inherited to another class in known as base class or parent class,
whereas the class that inherits a base class is known as derived or child class.
keyword ‘extends ‘ is used to used to inherit a class into another class.

Need of Inheritance

The base class simply defines the common functionality to be used by other classes. Once,
the base class is compiled and machine code is generated, you don’t need to recompile it
again at the time of accessing it into derived class. This feature is known as ‘Reuseability’.
Accessing Base Class Members:

Java does not allow to change the protection level of the base class members in the derived
class. Hence, the access specifier of the derived class in always public.
Private Member of a base class:
A class member declared private can never be used outside the class visibility even if the
class has been inherited to another class. Hence, private member of the base class are not
directly accessible to the derived class. But, if in any case such a situation arises that the
private members must be accessed then it can be done by using getters and setters.
Getter – It is a member method that is used to return the value of private member of base
class in derived class. The method getter is used in base class but it returns the value when
invoked in derived class. Getter is also helpful in accessing private member methods of base
class.

Setter – It is a member method which is used to feed the value in a private data member of
base class. You are well aware that base class is only a common code to be accessed by
various derived classes. Hence, the elements of base class are accessed through objects of
derived class. The need of using setter arises when the value to the private instance variable
of base class is to be provided through the object of derived class.
Illustration:
class ABC { class xyz extends ABC {
private int a; int x,s;
void SetA ( int a ){ void input ( int p ){
this.a = a; x = p;
} }
int GetA ( ){ int add ( ){
return a; s = x + GetA();
} return s; }
} }

TYPES OF INHERITANCE
1. Single Inheritance
if a base class is derived by a single derived class then it is called single inheritance.

This Photo by Unknown Author is


licensed under CC BY-SA-NC
2. Multiple Inheritance
When a derived class inherits from multiple base classes, it is known as multiple
inheritance.
3. Hierarchical Inheritance
When many derived classes inherit from single base class, it is known as hierarchical
inheritance.

4. Nested or Multilevel Inheritance

METHOD OVERRIDING
Sometimes we may need to perform similar tasks in the base class as well as in the derived
class. In such situation, it will be helpful and easy to access, if the methods in both the
classes are defined with the same name. Hence the technique by virtue of which the
methods are defined with same name in the base as well as derived class is known as
‘Method Overriding’.
Invoking overridden method
to invoke a over ridden method of the base class, the keyword ‘super ‘is used.
Syntax: super. < Overridden Method of base class>
// Illustration:
import java.util.*;
class pay{
String name;double basic;
void getdata(){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the name");
name=sc.next();
System.out.println("Enter the basic");
}
void display(){
System.out.println("Name\t"+name+"\t basic pay\t"+basic);
}
}
class salary extends pay{
double hra,da,gross;
void calculate(){
da=20.0/100*basic;
hra=15.0/100*basic;
gross=hra+da+basic;
}
void display(){
System.out.println("Gross pay\t"+gross);
}
void test(){
calculate();
super.display();
display();
}
}

DIFFERENCE BETWEEN METHOD OVERLOADING AND METHOD OVERRIDING

Method Overloading Method Overriding


A number of methods are defined with the A number of methods are defined with
same name in a single class same name in base as well as derived class
The overloaded method possesses different The overridden method may possess similar
parameters parameters.
It is an example of compile type It is an example of run time polymorphism
polymorphism
The return type can be same or different The return type will be same
SUPER CLASS CONSTRUCTOR
The constructor defined in the super class is involved with the help of ‘super’ keyword
Invoking Super Class Constructor
A constructor defined in the super class is not inherited to a sub class.
Syntax: super (Actual Parameters)

As soon as control encounters keyword super in the constructor of sub class, it moves to
execute super class constructor. In case super class constructor is parameterized then the
appropriate (actual) parameters need to be mentioned within braces along with super
keyword.
// Illustration:

class Employee{
String name;
Employee(String n){
name=n;
}
}
class Salary extends Employee{
String dept;double basic;
Salary(String nm,String dpt,double b){
super(nm); Invoking super class constructor Employee
dept=dpt;
basic=b;
}
}
}
PROGRAMS INVOLVING THE CONCEPT OF INHERITANCE:
A superclass Record contains names and marks of the students in two different single
dimensional arrays. Define a subclass Highest to display the names of the students
obtaining the highest mark
The details of the members of both classes are given below:

Class name: Record


Data member/instance variable:
n[] : array to store names
m[]: array to store marks
size: to store the number of students
Member functions/methods:
Record(int cap): parameterized constructor to initialize the data member
size = cap
void readarray() : to enter elements in both the arrays
void display() : displays the array elements

Class name: Highest


Data member/instance variable:
ind: to store the index
Member functions/methods:
Highest(…): parameterized constructor to initialize the data members of both the classes
void find(): finds the index of the student obtaining the highest mark and assign it to ‘ind’
void display(): displays the array elements along with the names and marks of the
students who have obtained the highest mark

Assume that the superclass Record has been defined. Using the concept of inheritance,
specify the class Highest giving the details of the constructor(…), void find() and void
display().
The superclass, main function and algorithm need NOT be written. [ICSE 2019]

class Highest extends Record{


int size;int ind,max;
Highest(int cap){
super(cap);
ind=0;
int m[]=new int[size];
String n[]=new String[size];
max=m[0];
}
void find(){
for(int i=0;i<size;i++){
if(m[i]>max){
max=m[i];
ind=i;
}
}
}
void display(){
super.display();
System.out.println("Highest mark obtained\t"+max);
System.out.println("Highest mark obatained by\t"+n[ind]);
}

A superclass Number is defined to calculate the factorial of a number. Define a subclass


Series to find the sum of the series S = 1! + 2! + 3! + 4! + ………. + n!

The details of the members of both classes are given below:


Class name: Number
Data member/instance variable:
n: to store an integer number
Member functions/methods:
Number(int nn): parameterized constructor to initialize the data member n=nn
int factorial(int a): returns the factorial of a number
(factorial of n = 1 × 2 × 3 × …… × n)
void display()

Class name: Series


Data member/instance variable:
sum: to store the sum of the series
Member functions/methods:
Series(…) : parameterized constructor to initialize the data members of both the classes
void calsum(): calculates the sum of the given series
void display(): displays the data members of both the classes
Assume that the superclass Number has been defined. Using the concept of inheritance,
specify the class Series giving the details of the constructor(…), void calsum() and void
display().
The superclass, main function and algorithm need NOT be written. [ICSE 2018]
class Series extends Number{
int sum;
Series(int num){
super(num);
sum=0;
}
void calsum(){
for(int i=1;i<=num;i++){
sum=sum+factorial();
}
}
void dislay(){
super.display();
System.out.println("The sum of the series is\t"+sum);
}

A superclass Product has been defined to store the details of a product sold by a
wholesaler to a retailer. Define a subclass Sales to compute the total amount paid by the
retailer with or without fine along with service tax.
Some of the members of both classes are given below:

Class name: Product


Data members/instance variables:
name: stores the name of the product
code: integer to store the product code
amount: stores the total sale amount of the product (in decimals)
Member functions/methods:
Product (String n, int c, double p): parameterized constructor to assign data members:
name = n, code = c and amount = p
void show(): displays the details of the data members

Class name: Sales


Data members/instance variables:
day: stores number of days taken to pay the sale amount
tax: to store the sen ice tax (in decimals)
totamt: to store the total amount (in decimals)
Member functions/methods:
Sales(….): parameterized constructor to assign values to data members of both the classes
void compute(): calculates the service tax @ 12.4% of the actual sale amount
calculates the fine @ 2.5% of the actual sale amount only if the amount paid by the
retailer to the wholesaler exceeds 30 days calculates the total amount paid by the retailer
as (actual sale amount + service tax + fine)
void show (): displays the data members of the superclass and the total amount

Assume that the superclass Product has been defined. Using the concept of inheritance,
specify the class Sales giving the details of the constructor (…), void compute() ) and void
show(). The superclass, main function and algorithm need NOT be written.
class Sales extends Product{
int day;double tax,totamt,fine;
Sales(String nm,int cod,int prc,int d){
super(nm,cod,prc);
day=d;
tax=0.0d;
totamt=0.0d;
fine=0.0d;
}
void compute(){
tax=12.4/100*prc;
if(day>30)
fine=2.5;

totamt=prc+tax+fine;
}
void show(){
super.show();
System.out.println("The Total amount payable is\t"+totamt);
}
}

A superclass Bank has been defined to store the details of a customer. Define a sub-class
Account that enables transactions for the customer with the bank. The details of both the
classes are given below:

Class name: Bank


Data members/instance variables:
name: stores the name of the customer
accno: stores the account number
P: stores the principal amount in decimals
Member functions/methods:
Bank(….): parameterized constructor to assign values to the instance variables
void display (): displays the details of the customer

Class name: Account


Data member/instance variable:
amt: stores the transaction amount in decimals
Member functions/methods:
Account(…): parameterized constructor to assign values to the instance variables of both
the classes
void deposit(): accepts the amount and updates the principal as p=p+amt
void withdraw(): accepts the amount and updates the principal as p=p-amt
If the withdrawal amount is more than the principal amount, then display the message
“INSUFFICIENT BALANCE”.
If the principal amount after withdrawal is less than 500, then a penalty is imposed by
using the formula.
p=p-(500-p)/10
void display(): displays the details of the customer

Assume that the superclass Bank has been defined.


Using the concept of Inheritance; specify the class Account giving details of the
constructor(…), void deposit(), void withdraw() and void display() The superclass and the
main function need not be written.
class Account extends Bank{
double amt;
Account(){
super();
amt=0;
}
void deposit(double a){
p=p+a;
}
void withdraw(double a){
p=p-a;
if(a>p){
System.out.println("Insufficient Balance");
}
else if(p<500){
p=p-(500-p)/10;
}
}
void display(){
super.display();
System.out.println("the Principal Amount is\t");
}
}

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

You might also like