COMPUTER CLASSES INheritance,Polymorphism and Interface
COMPUTER CLASSES INheritance,Polymorphism and Interface
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.
⚫ 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() {…}
}
Animal
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
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)
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
Animal
⚫ 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
+ 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() {…}
}
⚫ Program Size
⚫ Message-Passing Overhead
SUPER SUPER
extends extends
implement
extends
s
SUPER 1 SUPER 2
SUB
SUB
extends implement
extends
s
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;
Vehicle
SYNTAX:
Interface interface_name
{
Body of the interface
}
Defining an interface
For example:
{
double E = 2.718282;
}
Differences between classes and interfaces
⚫ The access specifiers public, private, protected are possible with classes,
but the interface uses only one specifier public.
⚫ Syntax:
access specifier class name implements interface1,
interface2, …, {
…
}
Example: Interface
Declaration of the Callback interface:
interface Callback
{
void callback(int param);
}
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
B extends A:
interface B extends A {
void meth3();
}
MyClass must implement all of
A and B methods:
class MyClass implements B
{
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.
❖ 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.
Syntax:
public default void getSides() {
// body of getSides()
}
Why default methods
❖ Suppose, we need to add a new method in an interface.
❖ However, that's not the end of the story. All our classes that implement
that interface must provide an implementation for the method.
❖ The Rectangle class provides the implementation of the getArea() method and
overrides the getSides() 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; }
} }
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