Вы находитесь на странице: 1из 33

Inheritance:

Inheritance allows classes to inherit commonly used instance variables and methods from other
classes.An inherited class will have all the features of its parent classes and can also have its own
instance variables and methods.

Keyword extends is used to inherit the superclass.


public class circle extends Shape
 The direct superclass of a subclass (specified by the keyword extends in the first line of a class
declaration) is the superclass from which the subclass inherits. An indirect superclass of a
subclassis two or more levels up the class hierarchy from that subclass.

 In single inheritance, a class is derived from one direct superclass. In multiple inheritance, a class
is derived from more than one direct superclass. Java does not support multiple inheritance.

 A subclass is more specific than its superclass and represents a smaller group of objects.

 Every object of a subclass is also an object of that class’s superclass. However, a superclass
object is not an object of its class’s subclasses.( Assigning base Class refrence to SuperClass)

 An is a relationship represents inheritance. In an is a relationship, an object of a subclass also


can be treated as an object of its superclass.

 The inheritance IS-A relationship works in only one direction! Triangle IS-A Shape makes sense,
so you can have Triangle extend Shape. But the reverse—Shape IS-A Triangle—does not make
sense, so Shape should not extend Triangle. Remember that the IS-A relationship implies that if
X IS-A Y, then X can do anything a Y can do (and possibly more)..Inheritance is not mutual.

 If class B extends class A, class B IS-A class A. This is true anywhere in the inheritance tree. If
class C extends class B, class C passes the IS-A test for both B and A.

• A has-a relationship represents composition. In a has-a relationship, a


class object contains references

to objects of other classes. Rectangle

public int length;


public int breadth;

public int area( );

Cuboid
public int height;

public int volume( );

1
A Simple inheritance program
 We say that the subclass extends the superclass. An inheritance relationship means that the
subclass inherits the members(the instance variables and methods.) of the superclass.

 subclass can add new methods and instance variables of its own, and it can override the
methods it inherits from the superclass

 When a class is inherited, the child class can access all features of the parent class as if it were
declared in its class.

Advantage: Once the class is developed and tested ,its code can be used by the other classes.Inheritance
avoid rewriting the code.

The Keyword extends is used to inherit the superclass

Rectangle.java //SuperClass
public class Rectangle {
int length;
int breadth;

public void showLengthBreadth()


{
System.out.println("Length = " + length + "\n" +
"Breadth = " + breadth );
}

//method for calculating area of Rectangle


public int area()
{
return length * breadth;
}

Cuboid.java //SubClass

public class Cuboid extends Rectangle {

int height;

public void showHeight() {


System.out.println("Height = " + height);
}
//method for calculating area of Rectangle
public float volume() {
return length * breadth * height;
}
}

2
RectCubTest.java

public class RectCubTest {

public static void main(String args[]) {

Rectangle r = new Rectangle();


r.length = 5;
r.breadth = 4;
System.out.println("Contents of SuperClass Rectangle are");
r.showLengthBreadth();
System.out.println("\n Area is = " + r.area());

Cuboid c = new Cuboid();


System.out.println("Contents of SubClass Cuboid are");
c.showLengthBreadth();
c.showHeight();
c.length = 7;
c.breadth = 6;
c.height = 8;
System.out.println("\n Volume is = " + c.volume());

}
}

OUTPUT

Contents of SuperClass Rectangle are


Length = 5
Breadth = 4
Area is = 20

Contents of SubClass Cuboid are


Length = 0
Breadth = 0
Height = 0
Volume is = 336.0

As you can see, the subclass Cuboid includes all of the members of its superclass, Rectangle.
This is why Cuboid RefrenceVariable “c” can access lenght and breadth and call
showLengthBreadth( ) method of its superClass(i. Rectangle.) Also, inside volume( ), length and
breadth are accessed directly as if they were the part of Cuboid.

A major advantage of inheritance is that once you have created a superclass that defines the
attributes common to a set of objects, it can be used to create any number of more specific
subclasses. Each subclass can precisely tailor its own classification

3
METHOD OVERIDING

Polymorphism: Method overriding is a form of polymorphism.


Polymorphism is essential to object-oriented programming for one reason: 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. Overridden methods are
another way that Java implements the “one interface, multiple methods” aspect of
polymorphism.

Method Overiding Rules

 Whatever the superclass takes as an argument, the subclass overriding the method must
use that same argument. And whatever the superclass declares as a return type, the
overriding method must declare either the same type, or a subclass type.

 The method can’t be less accessible.


That means the access level must be the same, or friendlier. That means you can’t, for
example, override a public method and make it private

super Keyword
 The super keyword is really a reference to the superclass portion of an object. When
subclass code uses super, as in super.runReport(), the superclass version of the method
will run.

The keyword super lets you invoke a superclass version of an overridden method, from within
the subclass.super.area();

4
public class Parallelogram
{

public int breadth;


private int height;

public void setHeight( int h )


{
height = ( h > 0) ? h: 1;
}
public int getHeight()
{
return height;
}
public float area()
{
return breadth * height;
}
}

5
Triangle.java
public class Triangle extends Parallelogram
{
public Triangle( )
{
super();// calling parallelogram constructor
}

//method for calculating area of triangle


public float area()
{
return 0.5f * super.area(); // calling area()of parallelogram
}
}

ParallelogramTriangleTest.java

public class ParalleogramTraingleTest {


public static void main(String args[])
{
Parallelogram p = new Parallelogram();
p.breadth = 4 ;
p.setHeight( 5 );
System.out.println("\n Area of Paralleogram = " + p.area());

Triangle t = new Triangle();


t.breadth = 6 ;
t.setHeight( 7 );
System.out.println("\n Area of Triangle is = " + t.area());
}

OUTPUT
Area of Paralleogram = 20.0
Area of Triangle is = 21.0

DYNAMIC METHOD DISPATCH: ( polymorphism)


 Method overriding forms the basis for one of Java’s most powerful concepts: dynamic
method dispatch.Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time. Dynamic method
dispatch is important because this is how Java implements run-time polymorphism

6
 When the compiler encounters a method call made through a variable, the compiler
determines if the method can be called by checking the variable’s class type. If that class
contains the proper method declaration (or inherits one), the call is compiled. At
execution time, the type of the object to which the variable refers determines the actual
method to use.

 Most method calls are resolved at execution time, based on the type of the object being
manipulated.
This process is known as dynamic binding or late binding.

 A superclass reference can be used to invoke only methods of the superclass (and the
superclass can invoke overridden versions of these in the subclass).

super KeyWord
 The super keyword is really a reference to the superclass portion of an object. When
subclass code uses super, as in super.volume(), the superclass version of the method will
run.
 The keyword super lets you invoke a superclass version of an overridden method, from
within the subclass .super.area();

The compiler decides whether you can call a method based on the reference type, not the actual
object type.

Shape

public int radius;


public int height;

public float volume( );

Cylinder

public float volume( );

Cone

public float volume( );

7
Shape.java

public class Shape {


public int radius;
public int height;

public Shape()
{
//Calling overloaded two argument constructor Shape(int r, int h )
this( 0, 0 );
}
public Shape( int r, int h )
{
radius = r;
height = h;
}
public float volume()
{
return 0.0f;
}
}

Sphere.java
public class Sphere extends Shape {
public Sphere()
{
super(); //calling Shape constructor
}
public Sphere(int r, int h )
{
super( r, h ); //calling Shape( int r, int h) constructor
}
public float volume()
{
return 3.14f * radius * radius * height;
}
}

Cone.java
public class Cone extends Sphere
{
public Cone(int r, int h)
{
super( r, h ); //calling Sphere( int r, int h) constructor
}

public float volume()


{
return 1/3f * super.volume(); //calling volume method of sphere
}
}

8
ShapeSphereConeTest.java

public class ShapeSphereConeTest {


public static void main(String argsp[])
{
Shape shpRef = new Shape();
System.out.println("Shape volume is = " + shpRef.volume());

Sphere sph = new Sphere( 4, 5 );


shpRef = sph; //Assigning subclass ref to superclass
System.out.println("Volume of Sphere is = " + shpRef.volume());

Cone con = new Cone( 6, 7 );


shpRef = con; //Assigning subclass ref to superclass
System.out.println("Volume of Cone is = " + shpRef.volume());

OUTPUT
Shape volume is = 0.0
Volume of Sphere is = 251.20001
Volume of Cone is = 263.76

Shape shpRef = new Shape();


Will create an refVariable shpRef of Shape.

Sphere sph = new Sphere( 4, 5 );


Will create an refVariable sph of Sphere.

shpRef = sph;
In java it is possible to assign a subclass reference to superclass.We are
assigning the subclass reference “sph” to the superClass reference variable
“shpRef”.

At the runtime JVM will call the method based on the type of object it is
referring to

shpRef.volume();
will call the overridden method declared in the Sphere class not the Shape
class

9
ABSTRACT CLASSES AND ABSTRACT METHDOS( polymorphism)
Polymorphism: Abstract Classes and Abstract Methods promotes polymorphism.
Polymorphism is essential to object-oriented programming for one reason: 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. Overridden methods are
another way that Java implements the “one interface, multiple methods” aspect of
polymorphism.
 Some classes just should not be instantiated!If we don’t want the class to be instantiated mark
the class abstract.

 There’s a simple way to prevent a class from ever being instantiated. In other words, to stop
anyone from saying “new” on that type. By marking the class as abstract, the compiler will stop
any code, anywhere, from ever creating an instance of that type.

 You can still use that abstract type as a reference type(to use it as a polymorphic argument or
return type, or to make a polymorphic array).

 Concrete classes are those that are specifi c enough to be instantiated. A concrete class just
means that it’s OK to make objects of that type.

Declaring an abstract class.


public abstract class Shape {

public abstract void area() ;

public abstract void volume();

 The compiler won’t let you instantiate an abstract class


 An abstract class can have both abstract and non-abstract methods
 An abstract class has virtually* no use, no value, no purpose in life, unless it is extended.

 An abstract class defines a common interface for the various members of a class hierarchy.
The abstract class contains methods that will be defined in the subclasses. All classes in the
hierarchy can use this same interface through polymorphism.

10
Abstract methods
An abstract class means the class must be extended; an abstract method means the method must be
overridden No method body !End it with a semicolon.
public abstract float area ();

 If you declare an abstract method, you MUST mark the class abstract as well. You can’t have
an abstract method in a non-abstract class.

 Abstract methods don’t have a body; they exist solely for polymorphism. That means the first
concrete class in the inheritance tree must implement all abstract methods.

 Implementing an abstract method is just like overriding a method.

 implement the abstract method”, that means you must provide a bodyThat means you must
create a non-abstract method in your class with the same method signature (name and
arguments) and a return type that is compatible with the declared return type of the abstract
method.

 If a subclass is derived from a superclass with an abstract method, and if no definition is


supplied in the subclass for that abstract method (i.e., if that method is not overridden in the
subclass), that method remains abstract in the subclass. Consequently, the subclass is also an
abstract class and must be explicitly declared as an abstract class.

abstract Shape3D

int radius;
int height;

public abstract double CSA();

RtCircularCylinder RtCircularCone

int slantHeight;

public double CSA();


public double CSA();

11
//Shape3D.java
public abstract class Shape3D {
public int radius;
public int height;

public Shape3D( int r, int h )


{
radius = r;
height = h;
}

public void setHeight( int h )


{
height = ( h > 0)? h : 1;
}
public int getHeight( )
{
return height;
}
public abstract double CSA(); //abstract method

public class RtCircularCylinder extends Shape3D {

public RtCircularCylinder( int r, int h )


{
super( r, h ); //calling shape3D constructor
}

//overriding abstract method of Shape3D.java


public double CSA()
{
return 2*Math.PI * radius * getHeight();
}
}

public class RtCircularCone extends Shape3D {

public double slantHeight;


l = √r2 + h2
public RtCircularCone(int r, int h ) where l = slant Ht
{
super( r, h );
slantHeight = Math.sqrt(( radius * radius ) +
(getHeight() * getHeight())) ;

}
public double CSA()
{
return Math.PI * radius * slantHeight;
}
}

12
//Shape3DTest.java

public class Shape3DTest {


public static void main( String args[] )
{
Shape3D shp; //cannot create object of abstract class

RtCircularCylinder rtCyl = new RtCircularCylinder( 4, 5 );


shp = rtCyl; //Assigning subclass refrence to superclass
System.out.println("\n CSA of RtCirculaCylinder is ="+ shp.CSA());

RtCircularCone rtCon = new RtCircularCone( 7, 8 );


shp = rtCon; //Assigning subclass refrence to superclass
System.out.println("\n CSA of RtCircularCone is =" + shp.CSA());
}

OUTPUT

CSA of RtCirculaCylinder is =125.66370614359172

CSA of RtCircularCone is =233.76911594312833

Shape3D shp;

RtCircularCylinder rtCyl = new RtCircularCylinder( 4, 5 );


shp = rtCyl;
shp.CSA()

At the runtime JVM will call the method based on the type of object it is
referring to.

shp.CSA(); will call the overridden method declared in the


RightCircularCylinder class

similarly for

RtCircularCone rtCon = new RtCircularCone( 7, 8 );


shp = rtCon;
shp.CSA();

shp.CSA(); will call the overridden method declared in the RightCircularCone


class

13
USING FINAL TO PREVENT INHERITANCE
A class declared final cannot be extended, and every method in it is implicitly final.

 A class that is declared final cannot be a superclass.

 It is illegal to declare a class as both abstract and final since an abstract class is incomplete by
itself and relies upon its subclasses to provide complete implementations.

abstract Employee

String name;
String empId

public abstract double salary( );

final HourlyWorker final Boss

public int wages; public int monthlySalary;


public int hours;
public double salary( );
public double salary( );

the method

public double salary() ; of


Employee.java HourlyWorker and Boss are
public abstract class Employee { implicitly marked as final.
String name;
String empId;

public Employee( String n, String eId )


{
name = n;
empId = eId;
}
public abstract double salary();

14
Boss.java

public final class Boss extends Employee {

public int monthlySalary;


public Boss(String n, String eId )
{
super( n, eId);
monthlySalary = 0;
}

//implementing the abstract method


public double salary()
{
return monthlySalary;
}
}

HourlyWorker.java

public final class HourlyWorker extends Employee {

public int wages;


public int hours;

public HourlyWorker( String n, String eId, int w, int h ) {


super( n , eId );
wages = w;
hours = ( h > 0 || h <= 24 ) ? h : 0;
}
//implementing the abstract method
public double salary()
{
return wages * hours;
}
}

EmployeeTest.java
public class EmployeeTest {
public static void main(String args[])
{
//can create only refvar “e” for abstract class(NO OBJECT CREATION)
Employee e;
Boss b = new Boss("Bushra", "E18");
b.monthlySalary = 50000;

e = b; // Assigning sublclass ref to superclass ref


System.out.println("Details of Boss");
System.out.println("name = " + e.name );
System.out.println("Boss eIS = " + e.empId);
System.out.println("Boss sal is = " + e.salary());

15
HourlyWorker hw = new HourlyWorker("Amina","E02", 200, 6);

e = hw;// Assigning sublclass ref to superclass ref

System.out.println("\nDetails of HourlyWorker");
System.out.println("name = " + e.name );
System.out.println("HourlyWorker eID = " + e.empId);
System.out.println("HourlyWorker wageRate = " + hw.wages);
System.out.println("HourlyWorker hoursWorked = " + hw.hours);
System.out.println("HourlyWorker sal is = " + e.salary());

}
}

OUTPUT
Details of Boss
name = Bushra
Boss eIS = E18
Boss sal is = 50000.0

Details of HourlyWorker
name = Amina
HourlyWorker eID = E02
HourlyWorker wageRate = 200
HourlyWorker hoursWorked = 6
HourlyWorker sal is = 1200.0

Employee e;
Boss b = new Boss("Bushra", "E18");
e = b; // Assigning sublclass ref to superclass ref
e.salary()

We are creating a reference variable of abstract class Employee.The


superclass reference will be used to call the methods polymorphically.

Boss b = new Boss("Bushra", "E18");


Now we are creating an object for Boss class referenced by “b”.

e = b; Assigning the base class refrence to superclass


At the runtime JVM will call the method based on the type of object it is
referring to.

e.salary()
will call the overridden method declared in the Boss class not the Employee
class

similarly for HourlyWorker also….

16
FINAL VARIABLES AND METHODS
variables can be declared final to indicate that they cannot be modified after they are declared and that
they must be initialized when they are declared.
It is also possible to define methods and classes with the final modifier.

A method that is declared final cannot be overridden in a subclass.

Methods that are declared static and methods that are declared private are implicitly final.

Because a final method’s definition can never change, the compiler can optimize the program by
removing calls to final methods and replacing them with the expanded code of their definitions
at each method call location—a technique known as inlining the code.

DIFFERENCES between INTERFACE and ABSTRACT CLASSES

Feature Interface Abstract class

Multiple inheritance A class may inherit A class may inherit only


several interfaces. one class.

Default implementation An interface cannot A class can provide


provide any code, just the complete, default code
signature. and/or just the details
that have to be
overridden.

Access Modfiers An interface cannot have An abstract class/(class)


access modifiers for the can contain access
subs, functions, modifiers for the subs,
properties etc everything functions, properties
is assumed as public

Core VS Peripheral Interfaces are used to An abstract class defines


define the peripheral the core identity of a class
abilities of a class. In and there it is used for
other words both Human objects of the same type.
and Vehicle can inherit
from a IMovable
interface.

17
Feature Interface Abstract class

Homogeneity If various If various


implementations only implementations are of
share method signatures the same kind and use
then it is better to use common behaviour or
Interfaces. status then abstract
class/(class) is better to
use.

Speed Requires more time to Fast


find the actual method in
the corresponding classes.

If we add a new method If we add a new method


to an Interface then we to an abstract class then
Adding functionality have to track down all the we have the option of
(Versioning) implementations of the providing default
interface and define implementation and
implementation for the therefore all the existing
new method. code might work
properly.

Fields and Constants Variables define in the An abstract class can


interface are implicitly have fields and constrants
final and static defined

methods All the methods of an An abstract class can


interface are abstract and have abstract and non
has to be implemented by abstract method.
the class .

18
Multiple Inheritance problem in java: Java does not promote multiple inheritance.i.e
extending from two class. But it isn’t, because multiple inheritance has a problem known as The
Deadly Diamond of Death.

CDBurner and
DVDBurner both

inherit from
DigitalRecorder,
Imagine that the “i” instance
and both override the variable is used by both
burn() CDBurner and DVDBurner, with
different values.

What happens if ComboDrive


needs to use both values of “i”
?

Problem with multiple


inheritance.

Which burn() method runs


when you

call burn() on the

 A Java interface solves your multiple inheritance problem by giving you much of the
polymorphic benefi ts of multiple inheritance without the pain and suffering from the
Deadly Diamond of Death (DDD).
 Interfaces are the ultimate in flexibility, because if you use interfaces instead of concrete
subclasses (or even abstract superclass types) as arguments and return types, you can pass
anything that implements that interface.

A class can extend one class, and implement an interface Use an interface when you want to
defi ne a role that other classes can play, regardless of where those classes are in the
inheritance tree.

19
A Java interface is like a 100% pure abstract class.

<<interface>>
Shape

public final static ONE = 1;

public abstract float area();


public abstract float volume();

 All methods in an interface are abstract, so any class that IS-A Shape MUST implement
(i.e. override) the methods of Shape.
 An interface is defined much like a class. This is the general form of an interface:

Create an interface using the interface keyword instead of the word class

interface methods are implicitly public and abstract,


public interface Shape {

public abstract float area();


public abstract float volume();

20
IMPLEMETING INTERFACES
Implement an interface using the keyword implements

To IMPLEMENT an interface:

public class Circle implements Shape {

//override all the abstract methods of Shape;

A class can implement multiple interfaces

public class Circle implements Shape, ShapeColor{

 When you implement an interface method, it must be declared as public.


 Leaving a method of an interface undefined in a class that implements the interface results in
a compile error indicating that the class must be declared abstract.

Accessing Implementations Through Interface References


When a class implements an interface, the same is a relationship provided by inheritance applies.
For example, class Circle implements Shape. Therefore, a Circle object is a Shape.

In fact, objects of any class that extends Circle are also Shape objects.

Cylinder extends Circle.


Cylinder objects is also a Shape Object.

subclasses refrences can be assigned to superclass refrences .


A refrence variable of any class that implements the interface can be assigned to the interface
refrence variable to promote polymorphism.

eg: Shape shp;


Circle c = new Circle();
shp = c;
shp.area();

When you call a method through one of these references, the correct version
will be called based on the actual instance of the interface being referred
to.

21
Shape.java
public interface Shape {
<<interface>>
public abstract float area(); Shape
public abstract float volume();

}
_______________________________________________
public abstract float area();
Circle.java public abstract float volume();
public class Circle implements Shape {
int radius;

public Circle(int r) {
radius = r; Circle
}

public float area()


public int radius;
{
return 3.14f * radius * radius; public float area()
} public float volume()
public float volume()
public String toString()
{
return 0.0f;
}

public String toString()


{ Cylinder
return "\n radius = " + radius;
} public int height;
}
public float area()
public float volume()
public class Cylinder extends Circle public String toString()
{
int height;

// Cylinder Two Argument constructor:


radius and height supplied,
public Cylinder(int r, int h)
{
super( r );
height = h;
}
//calculate the tptal surfacearea of the cylinder
public float area()
{
return 2 * super.area() +
2 * 3.14f * radius * height;
}

//method for calculating the volume of Cylinder


public float volume() {

return 3.14f * radius * radius * height;


}

22
//Convert instance variables of to a String representation
public String toString()
{
return super.toString() +
"\n height = " + height;
}
}
_______________________________________________________________________
ShapeTest.java
public class ShapeTest {
public static void main(String args[])
{
Shape shp;

Circle c = new Circle( 4 );


System.out.println("Implicit call to toString() of Circle"+ c );
System.out.println("Explicit call toString() of Circle" +
c.toString());

shp = c;//Assigning base class refrence to superClass


System.out.print("Area of Circle is = " + shp.area());
System.out.println("\n Volume of Circle is = "+ shp.volume());

Cylinder cyl = new Cylinder( 5, 6 );

shp = cyl; //Assigning base class refrence to superClass


System.out.println("Implicitly calling the toString() of +
“Cylinder"+shp );

System.out.println("Explicitly calling the toString() of Cylinder" +


cyl.toString());

System.out.print("Area of Cylinder is = " + shp.area());


System.out.println("\n Volume of Cylinder is = "+ shp.volume());
}
}

OUTPUT
Implicitly calling the toString() of Circle
radius = 4

Explicitly calling the toString() of Circle


radius = 4

Area of Circle is = 50.24


Volume of Circle is = 0.0

Implicitly calling the toString() of Cylinder


radius = 5
height = 6

Explicitly calling the toString() of Cylinder


radius = 5
height = 6

23
Area of Cylinder is = 345.40002
Volume of Cylinder is = 471.0

VARIABLES IN INTERFACES
Variables in an interface are implicitly marked as final and static.

Another use of interfaces is to define a set of constants that can be used in many class
definitions. Consider interface Constants
public interface Constants {
public static final int ONE = 1;
public static final int TWO = 2;
}
Classes that implement interface Constants can use ONE, TWO and THREE anywhere in the
class definition. A class can even use these constants by importing the interface, then referring to
each constant as Constants.ONE, Constants.TWO and Constants. THREE

<<interface>>
Constants

public static final int ONE = 1;


public static final int TWO = 2;
public static final int THREE = 3

public abstract int add();

Addition

public int add();


Constants.java
public interface Constants {

public final static int ONE = 1;


public final static int TWO = 2;
public final static int THREE = 3;

public abstract int add();

24
Addition.java

public class Addition implements Constants {

public int add()


{
int sum = Constants.ONE + Constants.TWO +Constants.THREE;
return sum;
}

ConstantsAdditionTest.java

public class ConstantsAdditionTest {


public static void main( String args[])
{
Constants con ;
Addition a = new Addition();
System.out.println("Sum of constans is = " + a.add());

//Assigning sublcass refrence to con


con = a;
System.out.println("Accessing add() through interfaceRef con");
System.out.println("Sum of Constants is = " + a.add());
}
}

OUTPUT

Sum of constans is 6

Accessing add() through interfaceRefrence con


Sum of constans is 6

Constants con ;
We are creating con reference variable referring to the Constants interface.

Cannot create an object of interface because interface contains abstract


methods

25
EXTENDING INTERFACES
One interface can inherit another by use of the keyword extends. The syntax is the same as for
inheriting classes. When a class implements an interface that inherits another interface, it must
provide implementations for all methods defined within the interface inheritance chain.

<<interface>>
A

public abstract void methodA();


public abstract void methodB();

<<interface>>
B

public abstract void methodC();

InterfaceExtension

A.java
public interface A
{
public abstract void methodA();
public abstract void methodB();

B.java

public interface B extends A


{
public abstract void methodC();
}

26
InterfaceExtension.java

public class InterfaceExtension implements B {


public void methodA()
{
System.out.println("Method A is overridden");
}

public void methodB()


{
System.out.println("method B is overridden");
}

public void methodC()


{
System.out.println("Method C is overridden");
}
}

IFExtTest.java

public class IFExtTest {


public static void main(String argsp[])
{
InterfaceExtension ifExt = new InterfaceExtension();
ifExt.methodA();
ifExt.methodB();
ifExt.methodC();

OUTPUT
Method A is overridden
method B is overridden
Method C is overridden

27
IMPLEMENTING MULTIPLE INTERFACE:
When a class implements multiple interface it has to override all the abstract methods declared in
the interface it is implmenting.
<<interface>>
Constants

public final static int ONE = 1;


public final static int TWO = 2;
public final static int THREE = 3;

<<interface>> <<interface>>
Multiplication Subtraction

public static final int FOUR = 4;


public static final int FIVE = 5;
public abstract int subtract(int a, int b);
public abstract int multiply(); public abstract int subtract();

An interface can have


Arithmetic overloaded abstract methods

abstract int subtract(int a, int b);


and
public int multiply();
abstract int subtract() are
public int subtract(int a, int b);
public int subtract(); overloaded methods of interface

Constants.java

public interface Constants {

public final static int ONE = 1;


public final static int TWO = 2;
public final static int THREE = 3;

28
Multiplication.java

public interface Multiplication


{
public static final int FOUR = 4;
public static final int FIVE = 5;

public abstract int multiply();

Subtraction.java

public interface Subtraction {

public abstract int subtract(int a, int b);


public abstract int subtract();//overloaded method

Arithmetic1.java

public class Arithmetic1 implements Multiplication,


Subtraction,Constants
{
public int multiply()
{
return Multiplication.FOUR * Multiplication.FIVE;

public int subtract(int a, int b)


{
return a - b;
}

public int subtract()


{
return Constants.THREE - Constants.ONE;
}

29
ArithmeticTest.java

public class ArithmeticTest {


public static void main(String args[])
{
Arithmetic1 arth = new Arithmetic1();

int product = arth.multiply();


System.out.println("Product = " + product);

int diff = arth.subtract( 6, 4 );


System.out.println("Difference = " + diff);

System.out.println("Calculating diff using constant variable


of Constants Interface");

diff = arth.subtract();
System.out.println("Difference = " + diff);

OUTPUT

Product = 20
Difference = 2

Calculating diff using constant variable of Constants Interface


Difference = 2

30
IMPLEMENTING MULTIPLE INTERFACE EXTRA

When a class implements multiple interface it has to override the abstract methods declared in
the interface.
The class must override all the abstract method of the different interfaces it is implementing.

<<interface>>
Multiplication

public abstract int addition(int a , int b);


public abstract int subtract(int a, int b);
public abstract int multiply(int multiplicand, int multiplier );
public abstract float division(int dividend, int divisor );

<<interface>>
Statistics
public static final float PI = 3.14f

public abstract float mean( int x1, int x2);

Calculator

public int addition(int a , int b);


public int subtract(int a, int b);
public int multiply(int multiplicand, int multiplier );
public float division(int dividend, int divisor );

public abstract float mean( int x1, int x2);

public interface Arithmetic {

public abstract int addition(int a , int b);


public abstract int subtract(int a, int b);
public abstract int multiply(int multiplicand, int multiplier
);
public abstract float division(int dividend, int divisor );

31
public interface Statistics {

public abstract float mean(int x1, int x2);

public class Calculator implements Arithmetic, Statistics {

public int addition( int a, int b)


{
return a + b;
}

public int subtract( int a, int b )


{
return a - b;
}

public int multiply(int a, int b )


{
return a * b;
}

public float division( int dividend, int divisor)


{
return (float)dividend/divisor;
}

public float mean( int x1, int x2)


{
float mean = (x1 + x2) / 2;
return mean;
}
}

32
public class CalculatorTest {
public static void main(String args[])
{
Arithmetic arth;
Calculator calc = new Calculator();
int sum = calc.addition( 2, 4 );
System.out.println("Addition Result = " + sum);

int diff = calc.subtract( 5, 6 );


System.out.println("Subtraction Result = " + diff);

//Assigning subclss refrence to arth( Arithmetic Interface ref variable)


arth = calc;
int product = arth.multiply( 7, 8);
System.out.println("Multiplication Result = " + product);

float division = arth.division( 9, 10 );


System.out.println("Division Result = " + division);

float meanVal = calc.mean( 10, 20 );


System.out.println("Mean Value = " + meanVal);

Statistics stat;

//Assigning Calculator class ref to interface Ref 'stat'


stat = calc;
meanVal = calc.mean( 30, 40 );
System.out.println(" Mean Value = " + meanVal);

OUTPUT

Addition Result = 6
Subtraction Result = -1
Multiplication Result = 56
Division Result = 0.9
Mean Value = 15.0
Mean Value = 35.0

33

Вам также может понравиться