Inheritance & Polymorphism
Inheritance & Polymorphism
Polymorphism
(OOP Concept)
Advance Programming
Inheritance
• Inheritance is a fundamental concept in object-oriented programming
(OOP) that allows a class to inherit properties and behaviors from a
parent class or superclass.
• Using inheritance, you can create a general class that 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.
Inheritance (contd.)
• In the terminology of Java, a class that is inherited is called a superclass.
• The class that does the inheriting is called a subclass.
• A subclass is a specialized version of a superclass.
• It inherits all of the members defined by the superclass and adds its own,
unique elements.
• To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.
• Syntax:
class subclass-name extends superclass-name { // body of class }
• In the sub class:
– In class header use the extends keyword to specify the superclass
– Only declare the additional fields and methods
– In subclass constructor call the superclass constructor via super
keyword
– (optionally) override superclass methods
Visibility
• public
– Any field or method specified as public can be used by any external class
– Class constructors, accessor methods should be specified as public
• private
– Any field or method specified as private can be used by code inside the
class
– Fields and internal helper methods should be private
• protected
– Any field or method specified as protected can be used by code
inside the class and in subclasses
• i.e. classes which inherit from the original class
Multiple Inheritance
• Multiple inheritance allows a class to be derived from two or more
classes, inheriting the members of all parents
– Collisions, such as the same variable name in two parents, have to
be resolved
• Java supports single inheritance, meaning that a derived class can
have only one parent class
• Java does not support multiple inheritance via two or more classes
Inheritance Hierarchy Example
Inheritance Relationships
• Inheritance creates an is-a relationship,
– I.e. the child is a specialized version of the parent
• A child class of one parent can be the parent of another child, forming
a class hierarchy.
• A subclass will inherit all attributes and operations defined in any of
its super classes
– Subclass may be augmented with additional attributes and
operations
– Subclass can override attributes and operations
Inheritance Hierarchy Example
Superclass – BankAccount (1)
public class BankAccount {
//fields
private String number;
private String name;
private double balance;
//default constructor
public BankAccount(){
number = "--------";
name = "--------";
balance = 0.0;
}
//overloaded constructor
public BankAccount(String accountNo, String accountName){
number = accountNo;
name = accountName;
balance = 0.0;
}
Superclass – BankAccount (2)
public String getAccountNo() {return number;}
public String getAccountName() {return name;}
public double getBalance() {return balance;}
public void setAccountName(String accountName)
{name=accountName;}
public void credit (double amount)
{balance = balance + amount;}
public void debit (double amount)
{balance = balance - amount;}
}
Banking Inheritance Example
• Subclass inherits the variables and methods defined by the super
class
public class CurrentAccount extends BankAccount
• Subclass specializes by adding its own members:
– fields: overdraftLimit
– methods: getOverdraftLimit()
setOverdraftLimit()
debit() - overridden
Adding constructors in a
subclass
• Super class constructors are not inherited by the sub class, even though they
have public visibility
– However we need to use the super class constructor in order to set up the
"parent's part" of the object
• The super reference is a reference to the super class of a sub class
– Whereas this is a reference to the class itself
• Super() is used to invoke the parent's constructor super(accountNo,
accountName);
• The sub class constructor specifies parameters to:
– Initialize fields from its super class
– And to initialize its own fields
Subclass Constructors
class CurrentAccount{
//default constructor
public CurrentAccount(String accountNo, String accountName)
{
//invoke the parent's constructor
super(accountNo, accountName);
//initialise field
overdraftLimit = 0.0;
}
//overloaded constructor
public CurrentAccount(String accountNo, String accountName, double
accountLimit){
super(accountNo, accountName);
overdraftLimit = accountLimit;
}
Public void debit(double amount){if(balance>overdraftlimit){
Super.debit(amount)}else{System.out.println(“Balance insufficient”);}}}
Overrriding methods
• A subclass can override the definition of an inherited method in
favour of its own
– Unless the original method is defined as final in the super class
• The new overridden version of the method must have the same
signature as the parent's method
– But can have a different body
• The type of the object executing the method determines which
version of the method is invoked
Complete Program
class BankAccount { //fields //invoke the parent's constructor
private String number; super(accountNo, accountName);
private String name; //initialise field
private double balance; overdraftlimit = 0.0;
}
//default constructor
public BankAccount() { //overloaded constructor
number = "--------"; public CurrentAccount(String accountNo, String accountName, double
name = "--------"; accountLimit) {
balance = 0.0; super(accountNo, accountName);
} overdraftlimit = accountLimit;
}
//overloaded constructor
public BankAccount(String accountNo, String accountName) { public void debit(double amount) {
number = accountNo; if (super.getBalance() > overdraftlimit) {
name = accountName; super.debit(amount);
balance = 0.0; } else {
} System.out.println("Balance insufficient");
public String getAccountNo() }
{return number;} }
public String getAccountName()
{return name;} }
public double getBalance() {return balance;} public class BankAccountDemo {
public void setAccountName(String accountName) public static void main(String[] args) {
{name=accountName;} BankAccount ba = new BankAccount();
public void credit (double amount) CurrentAccount cba = new CurrentAccount("1233555", "Akash", 0.0);
{balance = balance + amount;} cba.credit(555.5);
public void debit (double amount) System.out.println("Balance" + cba.getBalance());
{balance = balance - amount;} cba.debit(400);
} System.out.print("balance: " + cba.getBalance());
//default constructor }
class CurrentAccount extends BankAccount{
private double overdraftlimit; }
public CurrentAccount(String accountNo, String accountName) {
Overloading vs. Overriding
• Overloading
– Multiple methods with the same name in the same class, but with different
signatures (parameters)
– Allows similar operation to be defined in different ways for different
parameter
• Overriding
– Two methods with same name and the same signature
• Original version in a parent class
• Recoded version in a child class
– Allows a similar operation to be defined in different ways for different sub
classes
Advantages of Inheritance
• Code Reusability: Inheritance allows subclasses to reuse code from their parent classes,
reducing the amount of code that needs to be written and increasing efficiency.
• Modularity: Inheritance enables developers to break down complex systems into smaller,
more manageable components, which can be inherited and reused across multiple
projects.
• Polymorphism: Inheritance provides polymorphic behavior, allowing different subclasses
to be treated as instances of the same parent class. This allows for more flexible and
extensible code.
• Code Organization: Inheritance helps organize code by grouping related classes together
in a hierarchical structure, making it easier to navigate and maintain.
• Easy Maintenance: With inheritance, changes made to the parent class are automatically
propagated to all its child classes, reducing the amount of maintenance required for the
codebase.
Polymorphism
• Polymorphism is a fundamental concept in object-oriented
programming (OOP) that allows objects of different types to be
treated as instances of a common type.
• Polymorphism - The ability of a superclass variable to behave as a
subclass variable
• It allows a general class to specify methods that will be common to all
of its derivatives, while allowing subclasses to define the specific
implementation of some or all of those methods.
• If there was no polymorphism like in c; you have to define functions
with different names like to find the absolute value of integer is abs(),
for float is fabs(), for long is labs(), it will create complexity.
Types of Polymorphism
1. Compile Time Polymorphism/Static Polymorphism
• Different implementations of a method, depending on the type of object that
is passed to the method (Method overloading)
• Same Class
• Different Arguments (No. of arguments, Type of arguments, Sequence of arguments)
2. Runtime Polymorphism/Dynamic Polymorphism
• (Method Overriding: A common interface or behavior that can be
implemented by different classes in different ways)
• Different Classes in hierarchy relation
• Same Arguments (No. of arguments, Type of arguments, Sequence of arguments)
• Note: Return type of function can’t be used for polymorphism
• CurrentAccount acc1 = new
CurrentAccount("100003", "Mr Nasir", 100));
SavingsAccount acc2 = new
SavingsAccount("100005", "Mr Saeed", 5.0));
BankAccount ba1,ba2;
ba1= acc1;
ba2= acc2;
system.out.println(ba1.getBalance());
system.out.println(ba2.getBalance());
ba1.debit(200);
Accessing inherited methods
• When we call a method with multiple versions (overrides)
– JVM will use the method version which corresponds to the actual
object type (Dynamic method Dispatch)
• Not the reference type
– I.e. the overridden version will be used if appropriate
Accessing new methods
• When a new (not overridden) method has to be
accessed we have to apply a cast
– Casting to a CurrentAccount object
(CurrentAccount)ba1.setOverdraftLimit(amount);
– Casting to a SavingsAccount object
(SavingsAccount)ba2.addInterest();
• The cast allows the sub class object to overrule the super class reference
• Problem:
– Applying incorrect sub class will generate an exception!
– How can we tell which element should be cast?
instanceof Keyword
• Checking for CurrentAccount subclass
if ( ba1 instanceof CurrentAccount ){ }
• Checking for SavingsAccount subclass
if ( ba2 instanceof SavingsAccount ){ }
• Generally, use instanceof rarely
Example
abstract class Shape {
abstract double calculateArea(); @Override
} double calculateArea() {
return length * width;
class Circle extends Shape { }
private double radius; }