0% found this document useful (0 votes)
3 views30 pages

Bcs306a Java Module 3

Module 3 of OOPS with Java focuses on inheritance, a key concept in object-oriented programming that allows classes to inherit properties and behaviors from other classes. It covers various types of inheritance including single, multilevel, hierarchical, multiple, and hybrid inheritance, along with examples for each type. Additionally, it discusses member access, the use of the 'super' keyword, and the implications of private members in inheritance.

Uploaded by

hnharika05
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)
3 views30 pages

Bcs306a Java Module 3

Module 3 of OOPS with Java focuses on inheritance, a key concept in object-oriented programming that allows classes to inherit properties and behaviors from other classes. It covers various types of inheritance including single, multilevel, hierarchical, multiple, and hybrid inheritance, along with examples for each type. Additionally, it discusses member access, the use of the 'super' keyword, and the implications of private members in inheritance.

Uploaded by

hnharika05
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

OOPS WITH JAVA (BCS306A) MODULE 3

OOPS WITH JAVA (BCS306A)


MODULE – 3
Chapter – 1
INHERITANCE
 Inheritance is one of the cornerstones of object-oriented programming because it allows the
creation of hierarchical classifications.
 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.
 In the terminology of Java, a class that is inherited is called a superclass.
 The class that does the inheriting is called a subclass.
 Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance
variables and methods defined by the superclass and adds its own, unique elements.

INHERITANCE BASICS

 Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
 The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
 Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
The syntax of Java Inheritance

class subclass-name extends superclass-name


{
//methods and fields

 The extends keyword indicates for making a new class that derives from an existing class.
Terms used in Inheritance

 Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class.

[Link],SVCE 1
OOPS WITH JAVA (BCS306A) MODULE 3

INHERITANCE EXAMPLES
EXAMPLE 1:

// Parent class (Superclass)


class Shape {
String color;
Shape(String color)
{
[Link] = color;
}
void draw() {
[Link]("Drawing a " + color + " shape.");
}
}

// Child class (Subclass) inheriting from Shape


class Circle extends Shape {
double radius;
Circle(String color, double radius)
{
super(color); // Call the constructor of the superclass (Shape)
[Link] = radius;
}

// Additional method specific to Circle


double calculateArea() {
return [Link] * radius * radius;
}
}

public class ShapeInheritanceExample


{
public static void main(String[] args)
{
// Create an instance of the Circle class
Circle myCircle = new Circle("Red", 5.0);

// Access methods from the superclass (Shape)


[Link]();

// Access method specific to Circle


double area = [Link]();
[Link]("Area of the circle: " + area);

[Link],SVCE 2
OOPS WITH JAVA (BCS306A) MODULE 3
}
}
In the above example:

 The Shape class is the parent class (superclass) with a property for color and a method for
drawing.
 The Circle class is a child class (subclass) that inherits from Shape. It also has an additional
property for the radius and a method to calculate the area of the circle.
 In the main method, an instance of the Circle class is created (myCircle). We can use methods
from both the Shape class and the Circle class for this object.
 This example demonstrates how inheritance can be used to model relationships between
different types of shapes, with common properties and behaviors in the superclass and
specialized properties and behaviors in the subclass.
EXAMPLE 2:

// Create a superclass.
class A {
int i, j;
void showij()
{
[Link]("i and j: " + i + " " + j);
}
}

// Create a subclass by extending class A.


class B extends A
{
int k;
void showk()
{
[Link]("k: " + k);
}

void sum()
{
[Link]("i+j+k: " + (i+j+k));
}
}

class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();

[Link],SVCE 3
OOPS WITH JAVA (BCS306A) MODULE 3
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
[Link]("Contents of superOb: ");
[Link]();
[Link]();

/* The subclass has access to all public members of


its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;

[Link]("Contents of subOb: ");


[Link]();
[Link]();
[Link]();

[Link]("Sum of i, j and k in subOb:");


[Link]();
}
}

Output:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

TYPES OF INHERITANCE
There are five types of inheritance, they are:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
On the basis of class, there can be three types of inheritance in java:

 Single, Multilevel and Hierarchical.

[Link],SVCE 4
OOPS WITH JAVA (BCS306A) MODULE 3
In java programming, multiple and hybrid inheritance is supported through interface only.

SINGLE INHEITANCE:

 As the name suggests, this type of inheritance occurs for only a single class. Only one class is
derived from the parent class.
 In this type of inheritance, the properties are derived from a single parent class and not more
than that.
 As the properties are derived from only a single base class the reusability of a code is
facilitated along with the addition of new features.
The flow diagram of a single inheritance is shown below:

Two classes Class A and Class B are shown in Figure, where Class B inherits the properties of Class
A.
EXAMPLE OF SINGLE INHERITANCE:

class Shape
{
public void draw() {
[Link]("Drawing a shape");
}
}
class Rectangle extends Shape
{
public void drawRectangle() {
[Link]("Drawing a rectangle");
}
}
public class SingleInheritance
{
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle();
[Link](); // Inherited from Shape
[Link](); // Specific to Rectangle

[Link],SVCE 5
OOPS WITH JAVA (BCS306A) MODULE 3

}
}

Output:
Drawing a shape
Drawing a rectangle

MULTILEVEL INHERITANCE

 The multi-level inheritance includes the involvement of at least two or more than two classes.
 One class inherits the features from a parent class and the newly created sub-class becomes
the base class for another new class.
 As the name suggests, in the multi-level inheritance the involvement of multiple base classes
is there.
 In the multilevel inheritance in java, the inherited features are also from the multiple base
classes as the newly derived class from the parent class becomes the base class for another
newly derived class.
The flow diagram of a multilevel inheritance is shown below:

From the flow diagram, we can observe that Class B is a derived class from Class A, and Class C is
further derived from Class B.
EXAMPLE OF MULTILEVEL INHERITANCE

class Vehicle
{
public void move() {
[Link]("Vehicle is moving");
}
}

[Link],SVCE 6
OOPS WITH JAVA (BCS306A) MODULE 3

class Car extends Vehicle


{
public void accelerate() {
[Link]("Car is accelerating");
}
}

class SportsCar extends Car


{
public void boost() {
[Link]("SportsCar is boosting");
}
}
public class MultilevelInheritance
{
public static void main(String[] args)
{
SportsCar sportsCar = new SportsCar();
[Link](); // Inherited from Vehicle
[Link](); // Inherited from Car
[Link](); // Specific to SportsCar
}
}

Output:
Vehicle is moving
Car is accelerating
SportsCar is boosting

HIERARCHICAL INHERITANCE

 The type of inheritance where many subclasses inherit from one single class is known as
Hierarchical Inheritance.
 Hierarchical Inheritance a combination of more than one type of inheritance.
 It is different from the multilevel inheritance, as the multiple classes are being derived from
one superclass.
 These newly derived classes inherit the features, methods, etc, from this one superclass. This
process facilitates the reusability of a code and dynamic polymorphism (method overriding).
The flow diagram of a Hierarchical inheritance is shown below:

[Link],SVCE 7
OOPS WITH JAVA (BCS306A) MODULE 3

In Figure, we can observe that the three classes Class B, Class C, and Class D are inherited from the
single Class A. All the child classes have the same parent class in hierarchical inheritance.
EXAMPLE OF HIERARCHICAL INHERITANCE

class Shape
{
public void draw() {
[Link]("Drawing a shape");
}
}

class Circle extends Shape


{
public void drawCircle() {
[Link]("Drawing a circle");
}
}

class Square extends Shape


{
public void drawSquare() {
[Link]("Drawing a square");
}
}

public class HierarchicalInheritance


{
public static void main(String[] args)
{
Circle circle = new Circle();
[Link](); // Inherited from Shape
[Link](); // Specific to Circle

Square square = new Square();


[Link](); // Inherited from Shape

[Link],SVCE 8
OOPS WITH JAVA (BCS306A) MODULE 3
[Link](); // Specific to Square
}
}

Output:
Drawing a shape
Drawing a circle
Drawing a shape
Drawing a square

MULTIPLE INHERITANCE
 Multiple inheritances is a type of inheritance where a subclass can inherit features from more
than one parent class.
 Multiple inheritances should not be confused with multi-level inheritance, in multiple
inheritances the newly derived class can have more than one superclass.
 And this newly derived class can inherit the features from these superclasses it has inherited
from, so there are no restrictions.
 In java, multiple inheritances can be achieved through interfaces.
The flow diagram of a multiple inheritance is shown below:

Figure shows that Class C is derived from the two classes Class A and Class B. In other words it can
be described that subclass C inherits properties from both Class A and B.

HYBRID INHERITANCE

 Hybrid inheritance is a combination of more than two types of inheritances single and
multiple.
 It can be achieved through interfaces only as multiple inheritance is not supported by Java.
 However, it is important to note that Hybrid inheritance does not necessarily require the use
of Multiple Inheritance exclusively.

[Link],SVCE 9
OOPS WITH JAVA (BCS306A) MODULE 3
 It can be achieved through a combination of Multilevel Inheritance and Hierarchical
Inheritance with classes, Hierarchical and Single Inheritance with classes.
 Therefore, it is indeed possible to implement Hybrid inheritance using classes alone, without
relying on multiple inheritance type.
The flow diagram of hybrid inheritance is shown below:

MEMBER ACCESS AND INHERITANCE

 Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private.
 A class member that has been declared as private will remain private to its class. It is not
accessible by any code outside its class, including subclasses.
 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.
EXAMPLE:

/* In a class hierarchy, private members remain private to their class.


This program contains an error and will not compile.
*/
// Create a superclass.
class A
{
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A
{
int total;

[Link],SVCE 10
OOPS WITH JAVA (BCS306A) MODULE 3
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access
{
public static void main(String args[])
{
B subOb = new B();
[Link](10, 12);
[Link]();
[Link]("Total is " + [Link]);
}
}

This program will not compile because the reference to j inside the sum( ) method of B causes an
access violation. Since j is declared as private, it is only accessible by other members of its own class.
Subclasses have no access to it.

USING SUPER
 There will be times when you will want to create a superclass that keeps the details of its
implementation to itself (that is, that keeps its data members private).
 In this case, there would be no way for a subclass to directly access or initialize these variables
on its own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java
provides a solution to this problem.
 Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super.
 In Java, the super keyword is used to refer to the immediate parent class object. It is often
used to access the members (fields or methods) of the superclass when there is a need to
differentiate between the superclass and the subclass with the same name.
 super has two general forms. The first calls the superclass’ constructor. The second is used
to access a member of the superclass that has been hidden by a member of a subclass.

i) Using super to Call Superclass Constructors


The super() keyword is used to invoke the constructor of the superclass.
A subclass can call a constructor defined by its superclass by use of the following form of super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the superclass.
super( ) must always be the first statement executed inside a subclass’ constructor.

Example:
class Animal
{
Animal() {

[Link],SVCE 11
OOPS WITH JAVA (BCS306A) MODULE 3
[Link]("Animal constructor");
}
}

class Dog extends Animal


{
Dog() {
super(); // invoking the constructor of the superclass
[Link]("Dog constructor");
}
}

public class Example1 {


public static void main(String[] args) {
Dog myDog = new Dog();
}
}

Output:
Animal constructor
Dog constructor

ii) A Second Use for super


The second form of super acts somewhat like this, except that it always refers to the superclass of the
subclass in which it is used. This usage has the following general form:
[Link]
Here, member can be either a method or an instance variable.
This second form of super is most applicable to situations in which member names of a subclass hide
members by the same name in the superclass.

Example:
class Animal
{
String sound = "Animal Sound";
void makeSound() {
[Link](sound);
}
}

class Dog extends Animal


{
String sound = "Bark";
void makeSound() {
// Accessing the makeSound method of the superclass

[Link],SVCE 12
OOPS WITH JAVA (BCS306A) MODULE 3
[Link]();

// Accessing the sound field of the superclass


[Link]([Link]);

// Accessing the sound field of the subclass


[Link](sound);
}
}

public class Example2 {


public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
}
}

Output:
Animal Sound
Animal Sound
Bark

CREATING A MULTILEVEL HIERARCHY


Up to this point, we have been using simple class hierarchies that consist of only a superclass and a
subclass. However, you can build hierarchies that contain as many layers of inheritance as you like.
Certainly! A multilevel hierarchy in Java involves having a chain of classes where each class extends
the one above it. Here's an example of a simple multilevel hierarchy:

// Base class representing a geometric shape


class Shape {
void draw() {
[Link]("Drawing a generic shape");
}
}

// Subclass extending Shape for 2D shapes


class TwoDimensionalShape extends Shape {
void calculateArea() {
[Link]("Calculating area of a 2D shape");
}
}

// Subclass extending TwoDimensionalShape for specific 2D shape - Circle


class Circle extends TwoDimensionalShape {

[Link],SVCE 13
OOPS WITH JAVA (BCS306A) MODULE 3
void draw() {
[Link]("Drawing a circle");
}

void calculateArea() {
[Link]("Calculating area of a circle");
}
}

// Subclass extending TwoDimensionalShape for specific 2D shape - Rectangle


class Rectangle extends TwoDimensionalShape {
void draw() {
[Link]("Drawing a rectangle");
}

void calculateArea() {
[Link]("Calculating area of a rectangle");
}
}

public class Example3 {


public static void main(String[] args) {
// Creating instances of different shapes
Circle myCircle = new Circle();
Rectangle myRectangle = new Rectangle();

// Calling methods from the multilevel hierarchy


[Link]();
[Link]();

[Link]();
[Link]();
}
}

Output:
Drawing a circle
Calculating area of a circle
Drawing a rectangle
Calculating area of a rectangle

When Constructors Are Called


When a class hierarchy is created, in what order are the constructors for the classes that make up the
hierarchy called?

[Link],SVCE 14
OOPS WITH JAVA (BCS306A) MODULE 3
The answer is that in a class hierarchy, constructors are called in order of derivation, from superclass
to subclass. Further, since super( ) must be the first statement executed in a subclass’ constructor, this
order is the same whether or not super( ) is used. If super( ) is not used, then the default or
parameterless constructor of each superclass will be executed.
The following program illustrates when constructors are executed:

Example:
// Demonstrate when constructors are called.
// Create a super class.
class A
{
A( )
{
[Link]("Inside A's constructor.");
}
}

// Create a subclass by extending class A.


class B extends A
{
B( )
{
[Link]("Inside B's constructor.");
}
}

// Create another subclass by extending B.


class C extends B
{
C( )
{
[Link]("Inside C's constructor.");
}
}

class CallingCons
{
public static void main(String args[])
{
C c = new C();
}
}

Output:

[Link],SVCE 15
OOPS WITH JAVA (BCS306A) MODULE 3
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor

METHOD OVERRIDING
 In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass.
 When an overridden method is called from within a subclass, it will always refer to the version
of that method defined by the subclass. The version of the method defined by the superclass
will be hidden.
Example:
// Method overriding.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show()
{
[Link]("i and j: " + i + " " + j);
}
}

class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show()
{
[Link]("k: " + k);
}
}
class Override
{

[Link],SVCE 16
OOPS WITH JAVA (BCS306A) MODULE 3
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}

Output:
k: 3

Method overriding occurs only when the names and the type signatures of the two methods are
identical. If they are not, then the two methods are simply overloaded.

DYNAMIC METHOD DISPATCH


 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.
 A superclass reference variable can refer to a subclass object. Java uses this fact to resolve
calls to overridden methods at run time.
 When an overridden method is called through a superclass reference, Java determines which
version of that method to execute based upon the type of the object being referred to at the
time the call occurs. Thus, this determination is made at run time.
 When different types of objects are referred to, different versions of an overridden method
will be called.
 In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed.
 Therefore, if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable, different
versions of the method are executed.

Example:
// Dynamic Method Dispatch
class A
{
void callme()
{
[Link]("Inside A's callme method");
}
}

[Link],SVCE 17
OOPS WITH JAVA (BCS306A) MODULE 3
class B extends A
{
// override callme()
void callme()
{
[Link]("Inside B's callme method");
}
}

class C extends A
{
// override callme()
void callme()
{
[Link]("Inside C's callme method");
}
}

class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A

r = a; // r refers to an A object
[Link](); // calls A's version of callme

r = b; // r refers to a B object
[Link](); // calls B's version of callme

r = c; // r refers to a C object
[Link](); // calls C's version of callme
}
}

Output:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method

[Link],SVCE 18
OOPS WITH JAVA (BCS306A) MODULE 3
USING ABSTRACT CLASSES
 Data abstraction is the process of hiding certain details and showing only essential information
to the user. Abstraction can be achieved with either abstract classes or interfaces.
 The abstract keyword is a non-access modifier, used for classes and methods.
 Abstract class is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
 Abstract method can only be used in an abstract class, and it does not have a body. The body
is provided by the subclass (inherited from).
 An abstract class can have both abstract and regular methods.
 To declare an abstract method, use this general form:
abstract type name(parameter-list);
 As you can see, no method body is present.
 Any class that contains one or more abstract methods must also be declared abstract.
 To declare a class abstract, you simply use the abstract keyword in front of the class keyword
at the beginning of the class declaration. There can be no objects of an abstract class.
 That is, an abstract class cannot be directly instantiated with the new operator. Such objects
would be useless, because an abstract class is not fully defined. Also, you cannot declare
abstract constructors, or abstract static methods.
 Any subclass of an abstract class must either implement all of the abstract methods in the
superclass, or be itself declared abstract.
Example:
// A Simple demonstration of abstract.
abstract class A
{
abstract void callme();

// concrete methods are still allowed in abstract classes


void callmetoo()
{
[Link]("This is a concrete method.");
}
}

class B extends A
{
void callme()
{
[Link]("B's implementation of callme.");
}
}

class AbstractDemo
{

[Link],SVCE 19
OOPS WITH JAVA (BCS306A) MODULE 3
public static void main(String args[])
{
B b = new B();
[Link]();
[Link]();
}
}

Notice that no objects of class A are declared in the program. As mentioned, it is not possible to
instantiate an abstract class. One other point: class A implements a concrete method called callmetoo(
). This is perfectly acceptable. Abstract classes can include as much implementation as they see fit.

Although abstract classes cannot be used to instantiate objects, they can be used to create object
references, because Java’s approach to run-time polymorphism is implemented through the use of
superclass references. Thus, it must be possible to create a reference to an abstract class so that it can
be used to point to a subclass object.

USING final WITH INHERITANCE


The keyword final has three uses.
First, it can be used to create the equivalent of a named constant.
Second, it can be used to prevent overriding
Third, it ca be used to prevent inheritance

i) Using final to Prevent Overriding


While method overriding is one of Java’s most powerful features, there will be times when you will
want to prevent it from occurring.
To disallow a method from being overridden, specify final as a modifier at the start of its declaration.
Methods declared as final cannot be overridden. The following fragment illustrates final:

class A
{
final void meth()
{
[Link]("This is a final method.");
}
}

class B extends A
{
void meth() { // ERROR! Can't override.
[Link]("Illegal!");
}
}

[Link],SVCE 20
OOPS WITH JAVA (BCS306A) MODULE 3
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-
time error will result.

ii) Using final to Prevent Inheritance


Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As
you might expect, 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.

Here is an example of a final class:


final class A {
// ...
}

// The following class is illegal.


class B extends A { // ERROR! Can't subclass A
// ...
}

As the comments imply, it is illegal for B to inherit A since A is declared as final.

THE OBJECT CLASS


There is one special class, Object, defined by Java. All other classes are subclasses of Object. That
is, Object is a superclass of all other classes. This means that a reference variable of type Object can
refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type
Object can also refer to any array.
Object defines the following methods, which means that they are available in every object.

The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final.
Consider two methods equals( ) and toString( ).
 The equals( ) method compares the contents of two objects. It returns true if the objects are
equivalent, and false otherwise. The precise definition of equality can vary, depending on the
type of objects being compared.

[Link],SVCE 21
OOPS WITH JAVA (BCS306A) MODULE 3
 The toString( ) method returns a string that contains a description of the object on which it is
called. Also, this method is automatically called when an object is output using println( ).
Many classes override this method. Doing so allows them to tailor a description specifically
for the types of objects that they create.

[Link],SVCE 22
OOPS WITH JAVA (BCS306A) MODULE 3
CHAPTER – 2
INTERFACES
 An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a behavior.
 A Java interface contains static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction and
multiple inheritances in Java using Interface. In other words, you can say that interfaces can
have abstract methods and variables. It cannot have a method body. Java Interface also
represents the IS-A relationship.
 Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.
 Once interface is defined, any number of classes can implement an interface. Also, one class
can implement any number of interfaces.
 To implement an interface, a class must create the complete set of methods defined by the
interface. However, each class is free to determine the details of its own implementation. By
providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.
 Interfaces are designed to support dynamic method resolution at run time.

DEFINING AN INTERFACE
An interface is defined much like a class. This is the general form of an interface:
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
 When no access specifier is included, then default access results, and the interface is only
available to other members of the package in which it is declared.
 When it is declared as public, the interface can be used by any other code. In this case, the
interface must be the only public interface declared in the file, and the file must have the same
name as the interface.
 name is the name of the interface, and can be any valid identifier. The methods that are
declared have no bodies. They end with a semicolon after the parameter list. They are,
essentially, abstract methods; there can be no default implementation of any method specified
within an interface.

[Link],SVCE 23
OOPS WITH JAVA (BCS306A) MODULE 3
 Each class that includes an interface must implement all of the methods. Variables can be
declared inside of interface declarations.
 They are implicitly final and static, meaning they cannot be changed by the implementing
class. They must also be initialized. All methods and variables are implicitly public.

IMPLEMENTING INTERFACES
 Once an interface has been defined, one or more classes can implement that interface.
 To implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface.
 The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma. If a
class implements two interfaces that declare the same method, then the same method will be
used by clients of either interface.
 The methods that implement an interface must be declared public. Also, the type signature of
the implementing method must match exactly the type signature specified in the interface
definition.
EXAMPLE:

interface Callback
{
void callback(int param);
}

class Client implements Callback


{
// Implement Callback's interface
public void callback(int p)
{
[Link]("callback called with " + p);
}

void nonIfaceMeth()
{
[Link]("Classes that implement interfaces " + "may also define other members,
too.");
}
}
class TestIface
{

[Link],SVCE 24
OOPS WITH JAVA (BCS306A) MODULE 3
public static void main(String args[])
{
Callback c = new Client();
[Link](42);
}
}

Output:
callback called with 42

DEFAULT INTERFACE METHODS


 Interfaces can have default methods, which provide a way to add new methods to interfaces
without breaking existing implementations.
 Default methods have an implementation in the interface itself and are marked with the default
keyword.
 If a new method was introduced in an interface then all the implementing classes used to
break, need to provide the implementation of that method in all the implementing classes.
 However, sometimes methods have only single implementation and there is no need to
provide their implementation in each class. In that case, we can declare that method as a
default in the interface and provide its implementation in the interface itself.
Syntax:
interface InterfaceName
{
// Abstract method(s)
void abstractMethod1();
void abstractMethod2();

// Default method with an implementation


default void defaultMethod()
{
// Implementation code for the default method
}
}

 Abstract Methods are the methods without a body (implementation). They are the core
methods that implementing classes must provide concrete implementations for.
 Default Method is a method with the default keyword preceding its declaration. It includes a
default implementation within the interface itself. Classes that implement the interface can
choose to use the default implementation or override it with their own.

EXAMPLE:
// Define an interface with a default method
interface Vehicle
{

[Link],SVCE 25
OOPS WITH JAVA (BCS306A) MODULE 3
void start(); // Abstract method
void stop(); // Another abstract method

default void honk()


{
[Link]("Vehicle is honking."); // Default method with implementation
}
}

// Implement the Vehicle interface in a Car class


class Car implements Vehicle
{
@Override
public void start() {
[Link]("Car is starting.");
}

@Override
public void stop() {
[Link]("Car is stopping.");
}

// Additional methods specific to the Car class


public void drive() {
[Link]("Car is in motion.");
}
}

// Main class to demonstrate the interface and its implementation


public class InterfaceExample {
public static void main(String[] args) {
// Create an instance of the Car class
Car myCar = new Car();

// Call methods from the Vehicle interface


[Link]();
[Link]();

// Call the default method added in the interface


[Link]();

// Call an additional method from the Car class


[Link]();
}

[Link],SVCE 26
OOPS WITH JAVA (BCS306A) MODULE 3
}

In this example, the Vehicle interface has a default method named honk(). The Car class implements
this interface but does not provide an explicit implementation for the honk() method. Since it's a
default method, the interface provides a default implementation that can be used by any class
implementing the interface. The Car class can still override the honk() method if needed.

When you run the InterfaceExample class, you'll see that the honk() method is called on the myCar
instance, and it prints "Vehicle is honking." This demonstrates the use of default methods in
interfaces.

USE static METHODS IN AN INTERFACE


 Static Methods in Interface are those methods, which are defined in the interface with the
keyword static.
 Unlike other methods in Interface, these static methods contain the complete definition of the
function and since the definition is complete and the method is static, therefore these methods
cannot be overridden or changed in the implementation class.
 Similar to Default Method in Interface, the static method in an interface can be defined in the
interface, but cannot be overridden in Implementation Classes.
 To use a static method, Interface name should be instantiated with it, as it is a part of the
Interface only.
 These methods are associated with the interface itself rather than instances of the interface.

Syntax
interface InterfaceName {
// Abstract method(s)
void abstractMethod();

// Default method with an implementation


default void defaultMethod() {
// Implementation code for the default method
}

// Static method with implementation


static void staticMethod() {
// Implementation code for the static method
}
}

EXAMPLE:
interface MathOperation
{
// Abstract method
int operate(int a, int b);

[Link],SVCE 27
OOPS WITH JAVA (BCS306A) MODULE 3

// Default method with an implementation


default void displayResult(int result) {
[Link]("Result: " + result);
}

// Static method with implementation


static void welcome() {
[Link]("Welcome to Math Operations!");
}
}
class Addition implements MathOperation
{
@Override
public int operate(int a, int b) {
return a + b;
}
}

class Subtraction implements MathOperation


{
@Override
public int operate(int a, int b) {
return a - b;
}
}

public class Example5 {


public static void main(String[] args) {
// Call static method from the interface
[Link]();

// Use classes implementing the interface


Addition add = new Addition();
int sum = [Link](5, 3);
[Link](sum);

Subtraction subtract = new Subtraction();


int difference = [Link](8, 4);
[Link](difference);
}
}

PRIVATE INTERFACE METHODS

[Link],SVCE 28
OOPS WITH JAVA (BCS306A) MODULE 3
 Private methods can be added to interfaces in Java.
 Private methods can be implemented static or non-static.
 This means that in an interface we are able to create private methods to encapsulate code from
both default and static public method signatures.
EXAMPLE:
public interface Foo {

default void bar() {


[Link]("Hello");
baz();
}

private void baz() {


[Link](" world!");
}
}

bar() is able to make use of the private method baz() by calling it from it’s default method.
Next, let’s add a statically defined private method to our Foo interface:

public interface Foo {

static void buzz() {


[Link]("Hello");
staticBaz();
}

private static void staticBaz() {


[Link](" static world!");
}
}

Within the interface, other statically defined methods can make use of these private static methods.
Finally, let’s call the defined default and static methods from a concrete class:

public class CustomFoo implements Foo {

public static void main(String... args) {


Foo customFoo = new CustomFoo();
[Link]();
[Link]();
}
}

[Link],SVCE 29
OOPS WITH JAVA (BCS306A) MODULE 3
The output is the string “Hello world!” from the call to the bar() method and “Hello static world!”
from the call to the buzz() method.

Benefits of private methods in interfaces


 Interfaces are able to use private methods to hide details on implementation from classes that
implement the interface.
 As a result, one of the main benefits of having these in interfaces is encapsulation.
 Another benefit is (as with private methods in general) that there is less duplication and more
re-usable code added to interfaces for methods with similar functionality.

[Link],SVCE 30

You might also like