0% found this document useful (0 votes)
4 views

COMPUTER CLASSES INheritance,Polymorphism and Interface

The document discusses inheritance in object-oriented programming, particularly in Java, explaining the relationships between parent and child classes, method overriding, and the use of visibility modifiers. It highlights the benefits and costs of inheritance, including code reuse and program complexity, and introduces concepts like polymorphism and the final keyword. Additionally, it covers class hierarchies, member access rules, and the significance of the 'super' keyword in accessing superclass members.

Uploaded by

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

COMPUTER CLASSES INheritance,Polymorphism and Interface

The document discusses inheritance in object-oriented programming, particularly in Java, explaining the relationships between parent and child classes, method overriding, and the use of visibility modifiers. It highlights the benefits and costs of inheritance, including code reuse and program complexity, and introduces concepts like polymorphism and the final keyword. Additionally, it covers class hierarchies, member access rules, and the significance of the 'super' keyword in accessing superclass members.

Uploaded by

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

INHERITANCE

Inheritance relationships are often shown graphically in a class diagram, with the
arrow pointing to the parent class

Animal
weight : int
Inheritance
+ getWeight() : int should create an
is-a relationship,
meaning the
Bird child is a more
specific version
of the parent
+ fly() : void
108
Inheritance
⚫ Inheritance allows a software developer to reuse classes by
deriving a new class from an existing one.

⚫ The existing class is called the parent class, or superclass,


or base class

⚫ The derived class is called the child class or subclass.

⚫ As the name implies, the child inherits characteristics of


the parent.

⚫ That is, the child class inherits the methods and data
defined for the parent class
107
Deriving Subclasses
⚫ In Java, we use the reserved word extends to establish an
inheritance relationship
class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}

class Bird extends Animal


{
// class contents
public void fly() {…};
}
109
Class Hierarchy
⚫ A child class of one parent can be the parent of another
child, forming class hierarchies

Animal

Reptile Bird Mammal

Snake Lizard Parrot Horse Bat

 At the top of the hierarchy there’s a default class


called Object. 110
Class Hierarchy
⚫ Good class design puts all common features as high in the
hierarchy as reasonable
⚫ inheritance is transitive
⚫ An instance of class Parrot is also an instance of Bird, an instance of
Animal, …, and an instance of class Object
⚫ The class hierarchy determines how methods are executed:
⚫ Previously, we took the simplified view that when variable v is an
instance of class C, then a procedure call v.proc1() invokes the
method proc1() defined in class C
⚫ However, if C is a child of some superclass C’ (and hence v is both
an instance of C and an instance of C’), the picture becomes more
complex, because methods of class C can override the methods of
class C’ (next two slides).

111
Defining Methods in the Child Class:
Overriding by Replacement
⚫ A child class can override the definition of an inherited method in
favorof its own
⚫ that is, a child can redefine a method that it inherits from its parent
⚫ the new method must have the same signature as the parent's method,
but can have different code in the body

⚫ In java, all methods except of constructors override the methods of


their ancestor class by replacement. E.g.:
⚫ the Animal class has method eat()
⚫ the Bird class has method eat() and Bird extends Animal
⚫ variable b is of class Bird, i.e. Bird b = …
⚫ b.eat() simply invokes the eat() method of the Bird class

⚫ If a method is declared with the final modifier, it cannot be


overridden

112
Defining Methods in the Child Class:
Overriding by Refinement
⚫ Constructors in a subclass override the definition of an inherited constructor
method by refining them (instead of replacing them)
- Assume class Animal has constructors
Animal(), Animal(int weight), Animal(int weight, int livespan)
- Assume class Bird which extends Animal has constructors
Bird(), Bird(int weight), Bird(int weight, int livespan)

- Let’s say we createa Bird object, e.g. Bird b = Bird(5)


- This will invoke first the constructorof the Animal (the superclass of Bird) and
then the constructor of the Bird

⚫ This is called constructor chaining: If class C0 extends C1 and C1 extends C2


and … Cn-1 extends Cn = Object then when creating an instance of object C0
first constructor of Cn is invoked, then constructors of Cn-1, …, C2, C1, and
finally the constructor of C
- The constructors (in each case) are chosen by their signature, e.g. (), (int), etc…
- If no constructor with matching signature is found in any of the class Ci for i>0 then the
default constructor is executed for that class
- If no constructor with matching signature is found in the class C0 then this causes a
compiler errorFirst the new method must have the same signature as the parent's method,
but can have different code in the body

113
Recap:

Class Hierarchy
In Java, a class can extend a single other class
(If none is stated then it implicitly extends an Object class)
Animal

Reptile Bird Mammal

Snake Lizard Parrot Horse Bat

 Imagine what would happen to method handling


rules if every class could extend two others…
(Answer: It would create multiple problems!) 114
Hierarchical Abstraction
⚫ An essential element of object-oriented programming is
abstraction.

⚫ Humans manage complexity through abstraction. For


example, people do not think of a car as a set of tens of
thousands of individual parts. They think of it as a well-
defined object with its own unique behavior.

⚫ This abstraction allows people to use a car without being


overwhelmed by the complexity of the parts that form the
car. They can ignore the details of how the engine,
transmission, and braking systems work.

⚫ Instead they are free to utilize the object as a whole.


Class Hierarchy
⚫ A child class of one parent can be the parent of another
child, forming class hierarchies

Animal

Reptile Bird Mammal

Snake Lizard Parrot Horse Bat

 At the top of the hierarchy there’s a default class called Object.


Class Hierarchy
⚫ Good class design puts all common features as high in
the hierarchy as reasonable

⚫ The class hierarchy determines how methods are


executed

⚫ inheritance is transitive
⚫ An instance of class Parrot is also an instance of Bird,
an instance of Animal, …, and an instance of class
Object
Base Class Object
⚫ In Java, all classes use inheritance.
⚫ If no parent class is specified explicitly, the base class Object is
implicitly inherited.
⚫ All classes defined in Java, is a child of Object class, which provides
minimal functionality guaranteed to e common to all objects.
⚫ Methods defined in Object class are;
1. equals(Object obj): Determine whether the argument object is the
same as the receiver.
2. getClass(): Returns the class of the receiver, an object of type Class.
3. hashCode(): Returns a hash value for this object. Should be
overridden when the equals method is changed.
4. toString(): Converts object into a string value. This method is also
often overridden.
Base class
1) a class obtains variables and methods from another class
2) the former is called subclass, the latter super-class (Base class)
3)a sub-class provides a specialized behavior with respect to its
super-class
4)inheritance facilitates code reuse and avoids duplication of
data
Extends
 Is a keyword used to inherit a class from another class
 Allows to extend f rom only one class
class One class Two extends One

{ int a=5; {

} int b=10;
}
Subclass
⚫ Methods allows to reuse a sequence of statements

⚫ Inheritance allows to reuse classes by deriving a new class from


an existing one

⚫ The existing class is called the parent class, or superclass, or base


class

⚫ The derived class is called the child class or subclass.

⚫ As the name implies, the child inherits characteristics of the


parent(i.e the child class inherits the methods and data defined
for the parent class
Subtype
⚫ Inheritance relationships are often shown graphically in
a class diagram, with the arrow pointing to the parent
class
Animal
weight : int

+ getWeight() : int

Bird

+ fly() : void
Substitutability (Deriving Subclasses)
⚫ In Java, we use the reserved word extends to establish an
inheritance relationship

class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}

class Bird extends Animal


{
// class contents
public void fly() {…};
}
Defining Methods in the Child Class:
Overriding by Replacement
⚫ A child class can override the definition of an inherited method in
favorof its own
⚫ that is, a child can redefine a method that it inherits from its parent
⚫ the new method must have the same signature as the parent's
method, but can have different code in the body

⚫ In java, all methods except of constructors override the methods


of their ancestorclass by replacement. E.g.:
⚫ the Animal class has method eat()
⚫ the Bird class has method eat() and Bird extends Animal
⚫ variable b is of class Bird, i.e. Bird b = …
⚫ b.eat() simply invokes the eat() method of the Bird class

⚫ If a method is declared with the final modifier, it cannot be


overridden
The Benefits of Inheritance
⚫ Software Reusability (among projects)
⚫ Increased Reliability (resulting from reuse and
sharing of well-tested code)
⚫ Code Sharing (within a project)
⚫ Software Components
⚫ Polymorphism (high-level reusable components)
⚫ Information Hiding
The Costs of Inheritance
⚫ Execution Speed

⚫ Program Size

⚫ Message-Passing Overhead

⚫ Program Complexity (in overuse of inheritance)


Types of inheritance
 Acquiring the properties of an existing Object into newly
creating Object to overcome the re-declaration of
properties in deferent classes.
 These are 3 types:
1. Simple Inheritance

SUPER SUPER

extends extends

SUB SUB 1 SUB 2


2. Multi Level 3. Multiple
Inheritance Inheritance
SUPER 1
SUPER SUPER 2

implement
extends
s
SUPER 1 SUPER 2
SUB
SUB
extends implement
extends
s

SUB SUB SUB


Member access rules
⚫ Visibility modifiers determine which class members are
accessible and which do not

⚫ Members (variables and methods) declared with public visibility


are accessible, and those with private visibility are not

⚫ Problem: How to make class/instance variables visible only to


its subclasses?

⚫ Solution: Java provides a third visibility modifier that helps in


inheritance situations: protected
Modifiers and Inheritance
(cont.)
Visibility Modifiers for class/interface:
public : can be accessed from outside the class definition.
protected : can be accessed only within the class definition in
which it appears, within other classess in the same package,
or within the definition of subclassess.
private : can be accessed only within the class definition in
which it appears.
default-access (if omitted) features accessible from inside the
current Java package
The protected Modifier
⚫ The protected visibility modifier allows a member of a base
class to be accessed in the child
⚫ protected visibility provides more encapsulation than
public does
⚫ protected visibility is not as tightly encapsulated as
private visibility

Book
protected int pages
+ getPages() : int
+ setPages(): void

Dictionary

+ getDefinitions() : int
+ setDefinitions(): void
+ computeRatios() : double
“super” uses
 ‘super’ is a keyword used to refer to hidden variables of super
class from sub class.
 super.a=a;

 It is used to call a constructor of super class from constructor of


sub class which should be first statement.
 super(a,b);

 It is used to call a super class method from sub class method to


avoid redundancy of code
 super.addNumbers(a, b);
Super and Hiding
⚫ Why is super needed to access super-class members?
⚫ When a sub-class declares the variables or methods with
the same names and types as its super-class:
class A {
int i = 1;
}
class B extends A {
int i = 2;
System.out.println(“i is “ + i);
}
⚫ The re-declared variables/methods hide those of the
super-class.
Example: Super and Hiding
class A {
int i;
}
class B extends A {
int i;
B(int a, int b) {
super.i = a; i = b;
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
Example: Super and Hiding
⚫ Although the i variable in B hides the i variable in A,
super allows access to the hidden variable of the
super-class:
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
Using final with inheritance
⚫ final keyword is used declare constants which can not
change its value of definition.

⚫ final Variables can not change its value.

⚫ final Methods can not be Overridden or Over Loaded

⚫ final Classes can not be extended or inherited


Preventing Overriding with final
⚫ A method declared final cannot be overridden in
any sub-class:
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
This class declaration is illegal:
class B extends A {
void meth() {
System.out.println("Illegal!");
}
}
Preventing Inheritance with final
⚫ A class declared final cannot be inherited – has no sub-
classes.
final class A { … }

⚫ This class declaration is considered illegal:


class B extends A { … }

⚫ Declaring a class final implicitly declares all its methods


final.

⚫ It is illegal to declare a class as both abstract and final.


Polymorphism
⚫ Polymorphism is one of three pillars of object-
orientation.

⚫ Polymorphism: many different (poly) forms of objects


that share a common interface respond differently when
a method of that interface is invoked:
1) a super-class defines the common interface

2) sub-classes have to follow this interface


(inheritance), but are also permitted to provide their
own implementations (overriding)
⚫ A sub-class provides a specialized behaviors relying on
the common elements defined by its super-class.
Polymorphism
⚫ A polymorphic reference can refer to different types of
objects at different times
⚫ In java every reference can be polymorphic except of
references to base types and final classes.

⚫ It is the type of the object being referenced, not the


reference type, that determines which method is invoked
⚫ Polymorphic references are therefore resolved at run-
time, not during compilation; this is called dynamic
binding

⚫ Careful use of polymorphic references can lead to elegant,


robust software designs
Method Overriding

⚫ When a method of a sub-class has the same name


and type as a method of the super-class, we say that
this method is overridden.

⚫ When an overridden method is called from within


the sub-class:
1) it will always refer to the sub-class method

2) super-class method is hidden


Example: Hiding with Overriding 1
class A {
int i, j;
A(int a, int b) {
i = a; j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
Example: Hiding with Overriding 2
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
System.out.println("k: " + k);
}
}
Example: Hiding with Overriding 3
⚫ When show() is invoked on an object of type B,
the version of show() defined in B is used:
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show();
}
}
⚫ The version of show() in A is hidden through
overriding.
Overloading vs. Overriding
⚫ Overloading deals with ⚫ Overriding deals with two
multiple methods in the methods, one in a parent
same class with the same class and one in a child
name but different class, that have the same
signatures signature
⚫ Overloading lets you
define a similar operation o Overriding lets you define a
in different ways for similar operation in
different data different ways for different
object types
Abstract Classes
⚫ Java allows abstract classes
⚫ use the modifier abstract on a class header to declare an
abstract class
abstract class Vehicle
{ … }
⚫ An abstract class is a placeholder in a class hierarchy
that represents a generic concept

Vehicle

Car Boat Plane


Abstract Class: Example
 An abstract class often contains abstract methods,
though it doesn’t have to
⚫ Abstract methods consist of only methods declarations,
without any method body
public abstract class Vehicle
{
String name;
public String getName()
{ return name; } \\ method body

abstract public void move();


\\ no body!
}
Abstract Classes
⚫ An abstract class often contains abstract methods, though it
doesn’t have to
⚫ Abstract methods consist of only methods declarations, without any
method body
⚫ The non-abstract child of an abstract class must override
the abstract methods of the parent
⚫ An abstract class cannot be instantiated
⚫ The use of abstract classes is a design decision; it helps us
establish common elements in a class that is too general to
instantiate
Abstract Method
⚫ Inheritanceallows a sub-class to override the methods of its
super-class.

⚫ A super-class may altogether leave the implementation details


of a method and declare such a method abstract:

⚫ abstract type name(parameter-list);

⚫ Two kinds of methods:


1) concrete – may be overridden by sub-classes
2) abstract – must be overridden by sub-classes

⚫ It is illegal to define abstract constructorsor static methods.


Defining an interface

⚫ An interface is syntactically similar to a class, but it lacks


instance variables and its methods are declared without any body.

⚫ An interface is defined with an interface keyword.

⚫ An interface declaration consists of modifiers, the interface, the


interface name, a comma-separated list of interfaces (if any), and the
interface body.

SYNTAX:

Interface interface_name
{
Body of the interface
}
Defining an interface
For example:

public interface GroupedInterface extends Interface 1,Interface 2,


Interface3

{
double E = 2.718282;

void doSomething (int i, double x);

int doSomethingElse(String s);

}
Differences between classes and interfaces

⚫ Interfaces are syntactically similar to classes, but they lack instance


variables, and their methods are declared without any body.

⚫ One class can implement any number of interfaces.

⚫ Interfaces are designed to support dynamic method resolution at run


time.

⚫ Interface is little bit like a class... but interface is lack in instance


variables....i.e., you can't create object for it.

⚫ Interfaces are developed to support multiple inheritance.


Differences between classes and interfaces

⚫ The access specifiers public, private, protected are possible with classes,
but the interface uses only one specifier public.

⚫ Interfaces contains only the method declarations.... no definitions.

⚫ A interface defines, which method a class has to implement.

⚫ The methods present in interfaces are pure abstract.


⚫ Two types of access:
1) public – interface may be used anywhere in a program
2) default – interface may be used in the current package
only

⚫ Interface methods have no bodies – they end with the


semicolon after the parameter list.

⚫ They are essentially abstract methods.

⚫ An interface may include variables, but they must be final,


static and initialized with a constant value.

⚫ In a public interface, all members are implicitly public.


Interface Implementation
⚫ A class implements an interface if it provides a complete set of
methods defined by this interface.

1) any number of classes may implement an interface

2) one class may implement any number of interfaces

⚫ Implementation relation is written with the implements


keyword.

⚫ Syntax:
access specifier class name implements interface1,
interface2, …, {

}
Example: Interface
Declaration of the Callback interface:
interface Callback
{
void callback(int param);
}

Client class implements the Callback interface:


class Client implements Callback
{
public void callback(int p)
{
System.out.println("callback called with " + p);
}
}
More Methods in Implementation
⚫An implementing class may also declare its own
methods:

class Client implements Callback {


public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement “ +
“interfaces may also define ” +
“other members, too.");
}
}
⚫ Interfaces and Extends both describe an “is- a” relation.

⚫ If B implements interface A, then B inherits the (abstract)


method signatures in A

⚫ If B extends class A, then B inherits everything in A.

⚫ which can include method code and instance variables as well


as abstract method signatures.

⚫ Inheritance” is sometimes used to talk about the superclass /


subclass “extends” relation only
Variables in interface

⚫ Variables declared in an interface must be constants.

⚫ A technique to import shared constants into multiple


classes:

1)declare an interface with variables initialized to the


desired values

2)include that interface in a class through


implementation.
Example: Interface Variables 1
An interface with constant values:

import java.util.Random;
interface SharedConstants
{
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
Example: Interface Inheritance 1

⚫Consider interfaces A and B.


interface A
{
void meth1();
void meth2();
}

B extends A:
interface B extends A {
void meth3();
}
MyClass must implement all of
A and B methods:
class MyClass implements B
{

public void meth1() {


System.out.println("Implement meth1().");
}

public void meth2() {


System.out.println("Implement meth2().");
}

public void meth3() {


System.out.println("Implement meth3().");
}
}
Main class for interface Inheritance
⚫ Create a new MyClass object, then invoke all interface
methods on it:

class IFExtend {
public static void main(String arg[])
{ MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Why do we use Interface?
1. In industry, architect-level people create interfaces, and then it is given to
developers for writing classes by implementing interfaces provided.

2. Using interfaces is the best way to expose our project’s API to some other projects.
In other words, we can provide interface methods to the third-party vendors for their
implementation.

For example, HDFC bank can expose methods or interfaces to various shopping carts.

3. Programmers use interface to customize features of software differently for


different objects.

4. It is used to achieve full abstraction in java.

5. By using interfaces, we can achieve the functionality of multiple inheritance.


Compiler role at interface level
❖ Java compiler automatically adds public and abstract keywords before to all
interface methods.

❖ Moreover, it also adds public, static, and final keywords before interface variables.
Extending Interface
Forms of Implementing Interface
default methods in Java Interfaces
❖ With the release of Java 8, we can now add methods with
implementation inside an interface.

❖ These methods are called default methods.

❖ To declare default methods inside interfaces, we use


the default keyword.

Syntax:
public default void getSides() {
// body of getSides()
}
Why default methods
❖ Suppose, we need to add a new method in an interface.

❖ We can add the method in our interface easily without implementation.

❖ However, that's not the end of the story. All our classes that implement
that interface must provide an implementation for the method.

❖ If a large number of classes were implementing this interface, we need to


track all these classes and make changes to them.

❖ This is not only tedious but error-prone as well.

❖ To resolve this, Java introduced default methods.

❖ Default methods are inherited like ordinary methods.


Default methods Example
interface Polygon { // implements the interface
void getArea(); class Square implements Polygon {
public void getArea() {
// default method int length = 5;
default void getSides() { int area = length * length;
System.out.println("I can get sides of a System.out.println("The area of the square is
polygon."); " + area);
} }
} }
class Main {
// implements the interface public static void main(String[] args) {
class Rectangle implements Polygon {
public void getArea() { // create an object of Rectangle
int length = 6; Rectangle r1 = new Rectangle();
int breadth = 5; r1.getArea();
int area = length * breadth; r1.getSides();
System.out.println("The area of the
rectangle is " + area); // create an object of Square
} Square s1 = new Square();
// overrides the getSides() s1.getArea();
public void getSides() { s1.getSides();
System.out.println("I have 4 sides."); }
} }
}
Default methods Example
Default methods
❖ In the above example, we have created an interface named Polygon. It has a
default method getSides() and an abstract method getArea().

❖ Here, we have created two classes Rectangle and Square that


implement Polygon.

❖ The Rectangle class provides the implementation of the getArea() method and
overrides the getSides() method.

❖ However, the Square class only provides the implementation of


the getArea() method.

❖ Now, while calling the getSides() method using the Rectangle object, the
overridden method is called.

❖ However, in the case of the Square object, the default method is called.
Program
// To use the sqrt function this.b = b;
import java.lang.Math; this.c = c;
s = 0;
interface Polygon { }
void getArea();
// calculate the area of a triangle
// calculate the perimeter of a Polygon public void getArea() {
default void getPerimeter(int... sides) { s = (double) (a + b + c)/2;
int perimeter = 0; area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
for (int side: sides) { System.out.println("Area: " + area);
perimeter += side; }
} }

System.out.println("Perimeter: " + perimeter); class Main {


} public static void main(String[] args) {
} Triangle t1 = new Triangle(2, 3, 4);

class Triangle implements Polygon { // calls the method of the Triangle class
private int a, b, c; t1.getArea();
private double s, area;
// calls the method of Polygon
// initializing sides of a triangle t1.getPerimeter(2, 3, 4);
Triangle(int a, int b, int c) { }
this.a = a; }
Program

You might also like