0% found this document useful (0 votes)
45 views61 pages

23 24 LP 21 ISC12 C12 Inheritance, Interface&polymorphism

The document discusses object-oriented programming concepts like inheritance, encapsulation, polymorphism and abstraction in Java. It defines inheritance as sharing variables and methods among classes through an "is-a" relationship. The key points covered are: 1. Inheritance allows code reusability and expressing real-world relationships between classes. It defines superclass, subclass and extends keyword. 2. Encapsulation wraps data and functions into a single unit called class. 3. Polymorphism is implemented using function overloading in Java. 4. Access specifiers like private, protected, public determine visibility of inherited members. Superclass constructors can be called from subclass using super().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views61 pages

23 24 LP 21 ISC12 C12 Inheritance, Interface&polymorphism

The document discusses object-oriented programming concepts like inheritance, encapsulation, polymorphism and abstraction in Java. It defines inheritance as sharing variables and methods among classes through an "is-a" relationship. The key points covered are: 1. Inheritance allows code reusability and expressing real-world relationships between classes. It defines superclass, subclass and extends keyword. 2. Encapsulation wraps data and functions into a single unit called class. 3. Polymorphism is implemented using function overloading in Java. 4. Access specifiers like private, protected, public determine visibility of inherited members. Superclass constructors can be called from subclass using super().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

INHERITANCE

ISC 12
SECTION C
concept
OBJECTIVES

To understand

Relationship with oops


The concept of inheritance in java
The various access specifiers and inheritance
Multiple classes and inheritance
 super()
Inheritance and constructors
Interface
Abstract classes
OOP
ENCAPSULATION
The wrapping up of data and functions (that operate on the data) into a single
unit called class.
For e.g.: Capsule

class Student
{ int roll, marks;
String name;
void enroll()
{ …..
}
void payFee( )
{ …..
}
void generateReportCard()
{ …..
}
}
Student raju = new Student( );
DATA ABSTRACTION
Act of representing essential features without including the
background details
E.g.: To learn how to drive a car we only need to know how to
use steering, accelerator, clutch ,brake and the gears. We need
NOT know how each of these work or the technology behind
it.
POLYMORPHISM
Ability for a message or data to be processed in more than one
form
This is implemented
using function overloading
FUNCTION OVERLOADING

When more than one functions have the same name but the type
and number of arguments (method signature) are different ,
they are said to be over loaded . Thus, parameter list of each
function should be unique. Function overloading implements
Polymorphism. For e.g.
int sample (int a)
int sample (int a , int c)
int sample (int a, String str)
FUNCTION OVERLOADING

Write a menu driven program with a function area( ) to calculate


and return the following
1. Area of trapezium
2. Area of rhombus
3. Area of circle
Hint: area of trapezium is ½(a+b)h and area of rhombus is
half of the product of its diagonals
WHAT IS INHERITANCE

Inheritance is a means of sharing variables and methods


among classes
Inheritance is an is-a relationship. We use inheritance only if
an is-a relationship is present between the two classes.
 Examples:
 A car is a vehicle.
 Orange is a fruit.
 A surgeon is a doctor.
 A dog is an animal.
EXAMPLE
NEED FOR INHERITANCE
• Code Reusability – A class can extend another class,
inheriting all its data members and methods
(redefining some of them and/or adding new ones)
• Transitive nature – if subclass B inherits properties
from class A, then all subclasses of B will
automatically inherit properties of A
• Capability to express real-world models. Inheritance
represents the is a relationship.
• For example: BMW is a car.
CODE REUSABILITY
Consider two Objects - Rectangle and Box

12
TRANSITIVE
Inheritance can be used to define a hierarchy of classes in an application:

Uniform

VSA

PHASE1 PHASE2
ISC

House TSHIRT&HALF TROUSERS House TSHIRT&FULL TROUSERS


EXAMPLES WHERE INHERITANCE
CAN BE USED
INHERITANCE TERMINOLOGY

subclass superclass
or extends or
derived class base class
Base Class: It is the class whose properties are inherited by
another class. It is also called Super Class.
Derived Class: It is the class that inherit properties from base
class. It is also called Sub Class.
EXAMPLE
GENERAL SYNTAX
class baseclass
{
public
private
protected

class derivedclassname extends baseclass


{

}
INHERITANCE IN JAVA
Inheritance is declared using the "extends" keyword

class Person
{ Person
String name; - name: String
Date dob; - dob: Date
[...]
}

class Employee extends Person


{
int employeID; Employee
int salary; - employeeID: int
Date doj;
- salary: int
[...]
- startDate: Date
}

Employee Ramesh = new Employee();


SUPER CLASS AND SUB CLASS

A class can be defined as a "subclass" of another


class.
The subclass inherits all data attributes of its
superclass
The subclass inherits all methods of its superclass

superclass: Person
- name: String
The subclass can: - dob: Date
Add new functionality
Use inherited functionality
Override inherited functionality
subclass:
Employee
- employeeID: int
- salary: int
- doj: Date
EXAMPLE -INHERITANCE
class Calculation public class My_Calculation extends Calculation
{
{ public void multiplication(int x, int y)
int z; {
z = x * y;
public void addition(int x, int y) System.out.println("The productis :"+z);
{ }
z = x + y; public static void main()
System.out.println("The sum is:"+z); {
int a = 20, b = 10;
}
My_Calculation demo = new My_Calculation();
public void Subtraction(int x, int y) demo.addition(a, b);
{ demo.Subtraction(a, b);
demo.multiplication(a, b);
z = x - y; }
System.out.println("The difference }
is:"+z);
}
} ASSIGNMENT 1-3
ASSIGNMENT 1
ASSIGNMENT 2
TYPES OF INHERITANCE

Not supported by java


TYPES OF INHERITANCE
Single Inheritance: one derived class inherits from one
base class.
Multiple Inheritance: one derived class inherits from
multiple base classes (NOT supported in Java)
Hierarchical Inheritance: multiple subclasses inherits
from one base class.
Multilevel Inheritance: subclass acts as a base class for
other classes.
Hybrid Inheritance: any legal combination of other
four types of inheritance.
ACCESS CONTROL OF INHERITED
MEMBERS
The access of inherited members
depends upon their access modifiers.
ACCESS SPECIFIER / VISIBILITY MODES

1. Private members are accessible only within the class. Only


methods that are part of the same class can access private
members.
2. Protected members are accessible within the class itself and
all its subclasses. (Restricts the visibility of members to only
classes in the same package and to inherited / derived classes
outside the package.)
3. Public members are accessible within the class and outside
the class.
class Student
{
public int roll;
private String name;
protected int marks;
}
ACCESS SPECIFIER

SUBCLASS NON-SUBCLASS

OWN SAME OTHER SAME OTHER


TYPE CLASS PACKAGE PACKAGE PACKAGE PACKAGE

PRIVATE YES NO NO NO NO

DEFAULT (friendly) YES YES NO NO NO

PROTECTED YES YES YES NO NO

PUBLIC YES YES YES YES YES


INHERITANCE AND CONSTRUCTORS
•Constructors of base class are not
inherited by subclass

•Constructors of Base class can be


called by a sub class using the
keyword super()

•Keyword super() must be the first


statement inside the constructor of
a subclass.

•When super() is not used in sub


class then the default constructor of
base class is automatically invoked.
DEFINING CONSTRUCTORS OF THE SUBCLASS

Call to constructor of superclass:


Must be first statement. Box()
Specified by super and the {
super();
parameter list. height = 0;
Rectangle() }
{
length=0;
Box(double l, double w, double h)
width= 0;
{
}
super(l, w);
Rectangle(double n1, double n2)
height = h;
{
}
length = n1;
width = n2;
}
30
EX1. PROBLEM USING CONSTRUCTORS class salary1 extends pay1
import java.util.*;
{
class pay1 double da,hra,gross;
{
String name; salary1()
{
double basic; super(); //base class constructor is used here
pay1() da=0;
{ hra=0;
gross=0;
name=""; }
basic=0; void calculate()
} {
getdata();
Scanner sc=new Scanner(System.in); da=.2*basic;
void getdata() hra=.15*basic;
{ gross=basic+da+hra;
}
System.out.println("Enter name and basic"); void display()
name=sc.next(); {
basic=sc.nextDouble(); System.out.println("da ="+da+"hra ="+hra+"gross ="+gross);
}
} void test()
void display1() {
{ calculate();
display1();
System.out.println("name"+name+"basic"+basic); display();
} }
} public static void main()
{
salary1 obj= new salary1();
obj.test();
}
}
EXAMPLE2 PROBLEM USING CONSTRUCTORS…PARAMETRISED
class compute extends library
class library {
{ int d,f;
compute(String cname,String cauthor,int ccp,int cd)
String name,author;int cp; {
library(String cname , String super(cname,cauthor,ccp);
cauthor , int ccp) d=cd;
{ f=0;
}
name =cname; void fine()
author=cauthor; {
if (d>=1 &&d<=5)
cp=ccp; f=2*d;
} else if(d<=10)
f=2*5+3*(d-5);
void show() else
{ f=2*5+3*5+5*(d-10);
}
System.out.print("\ void display()
nname="+name+"\ {
System.out.print("\nAmount payable is "+f );
nAuthor="+author+"cost }
price="+cp); public static void main()
{
} compute obj=new compute("isc","praveena",500,50);
} obj.fine();
obj.show();//from the base class
obj.display();
}
}

Ex2.Inheritance Practice
ASSIGNMENT 3
ASSIGNMENT 4
EXAMPLE3 PROBLEM USING CONSTRUCTORS
A class Employee contains employee details and another class Retire calculates the employee’s Provident Fund and
Gratuity. The details of the two classes are given below:
Class name : Employee
Data Members:
Name : stores the employee name
ID : stores the employee identification number
basicPay : stores the employee basic monthly salary (in decimals)
accNum : stores the employee bank account number
Member functions:
Employee ( …. ) : parameterized constructor to assign value to data members
void display( ) : to display the employee details

Class name : Retire


Data Members:
service : stores the employee years of service
Pf : stores the employee provident fund amount ( in decimals )
Gratuity : stores the employee gratuity amount ( in decimals )
Member functions:
Retire ( …. ) : parameterized constructor to assign value to data members of both
the classes.
void calculate( ) : calculates the PF as (2.5% of the basic pay) * years of service, If the years of
service >= 10 years then the gratuity amount is 2 years salary else gratuity is nil.
void show ( ) : Displays the employee details along with the PF (Provident Fund )
and gratuity amount.
class Employee
{ String name;
int ID, accNum;
double basicPay;
Employee (String str, int N, int M, double D)
{
name=str;
ID = N;
accNum=M;
basicPay = D;
}
public void display( )
{
System.out.println("Name: " +name +" ID: "+ID +"account no: "+accNum +"basic salary: "+ basicPay);
}
}
class Retire extends Employee
{ int service;
double Pf, Gratuity;
Retire (String str, int N,int M,, double D , int num)
{
super (str,N, M,D);
service=num;
Pf = Gratuity = 0.0;
}
public void calculate( )
{
Pf=0.025*basicPay;
if(service>=10)
Gratuity = basicPay*24;
else
Gratuity=0.0;
}
public void show( )
{
super.display( );
System.out.println ("Years in service: " + service +" Provident fund: "+ Pf +" Gratuity: "+Gratuity);
}
}
ASSIGNMENT 4-6
ASSIGNMENT 5
ASSIGNMENT 6
POLYMORPHISM IN JAVA

In the below Images, you can see, Man is only one, but he takes multiple
roles like - he is a dad to his child, he is an employee, a salesperson and
many more. This is known as Polymorphism.

Implementation of polymorphism is done using method overriding and overloading


OVERRIDING VS OVERLOADING
A method is overloaded if it has multiple definitions that are
distinguished from one another by having different numbers or
types of arguments
A method is overridden when a subclass gives a different
definition of the method with the same number and types of
arguments
All (non-private) methods of the base class are available in the derived class
You don’t need to have the source code of a class to extend it
METHOD OVERRIDING EXAMPLE
OVERRIDING IN INHERITANCE
To write a method’s definition of a subclass, specify a call to
the public method of the superclass.
 If subclass overrides a method of superclass, call the method of
superclass as given below:
super.MethodName(parameter list)
 If subclass does not override a method of superclass, call the method of
superclass as given below:
MethodName(parameter list)

42
EXAMPLE-OVERRIDING
// program to implement overriding with constructor inheritance
import java.util.*; class salary extends pay
class pay {
{ double da,hra,gross;
String name;
double basic; void calculate()
Scanner sc=new Scanner(System.in); {
void getdata() getdata();
{ da=.2*basic;
System.out.println("Enter name and basic"); hra=.15*basic;
name=sc.next(); gross=basic+da+hra;
basic=sc.nextDouble(); }
} void display()
void display() {
{ System.out.println("da"+da+"hra"+hra+"gross"+gross);
System.out.println("name"+name+"basic"+basic); }
} void test()
} {
calculate();
super.display();
display();
}
public static void main()
{
salary obj= new salary();
obj.test(); Ex.overriding-pay2
}
}
ASSIGNMENT 7
ABSTRACT CLASS

• Abstract Class- is one that represents a concept and


whose objects can't be created.
• A class that is declared with the reserved word abstract
in its heading.
• An abstract class can contain instance variables and
abstract methods .
• An abstract class should contain one or more abstract
methods.
• If a class contains an abstract method, the class must be
declared abstract.
• You can instantiate an object of a subclass of an abstract
class, but only if the subclass gives the definitions of all the
abstract methods of the superclass.

45
ABSTRACT CLASSES
• Abstract classes are only used as super classes
• Classes are declared as abstract classes only if they will never
be instantiated(ie.no object can be created)
• Abstract classes contain usually one or more abstract methods
• Example:
public abstract class Mouse
{

abstract void makeMove( );
}
ABSTRACT METHODS

Abstract methods have no body at all and just have


their headers declared with no body
The only way to use an abstract class is to create a
subclass that implements each abstract method
Example:
abstract void calculate( int N );
abstract void display( );
EXAMPLE
public abstract class shape
{
String name;
double area;
public abstract void calcarea(); // abstract methods end with a semicolon
}
class circle extends shape
{
double radius;
public void calcarea()
{ area=3.14 *radius*radius;
System.out.println(area);}
}
class rectangle extends shape
{
double length,breadth;
public void calcarea() SOME MORE EXAMPLES
{ area=length*breadth;
System.out.println(area);}
}
ASSIGNMENT 8
ASSIGNMENT 9A
FINAL CLASSES
• You can declare a method of a class final using the keyword
final. For example, the following method is final.

public final void doSomeThing()


{
//...
}

• If a method of a class is declared final, it cannot be


overridden with a new definition in a derived class.
• In a similar manner, you can also declare a class final using
the keyword final.
• If a class is declared final, then no other class can be
derived from this class.
INTERFACES
An Interface defines a protocol of behavior.
Interface dictates common behavior among objects from
diverse classes.[ to tie elements of different classes together]
Keyword interface is used to define it
syntax
interface interface_name
{ body }

The interface body can declare only 2 things


• Abstract methods
• Constants - variables that cannot be modified using 'public
static final'
IMPLEMENTATION OF INTERFACE

A class implements an interface using 'implements' keyword


A class can implement many interfaces

Ex. Interface
DIFFERENCES BETWEEN AN INTERFACE AND MULTIPLE
INHERITANCE

Only constants can be inherited from interfaces unlike in


multiple inheritance
An interface cannot implement any method
An interface is not part of the class hierarchy
EXAMPLE
interface student
{
public static final long indexnum;

public void elective();


public void fees();
}

public class UG implements student


{
String subjects[]=new subjects[5];
double feeamt;
public void elective()// MUST DECLARE FNS AS PUBLIC
{ Sytem.out.println("Choose elective"); --------}

public void fees() // MUST DECLARE FNS AS PUBLIC


{ feeamt=60000; ---}

}
PROGRAMS-PAST EXAM PAPERS
ASSIGNMENT 10 - ISC2016
ASSIGNMENT 11 - ISC2017
ASSIGNMENT 12 - ISC 2018
ASSIGNMENT 13 - ISC 2019
THANK YOU........

You might also like