0% found this document useful (0 votes)
4 views25 pages

Java Module 3

Uploaded by

bharathbalaji701
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 views25 pages

Java Module 3

Uploaded by

bharathbalaji701
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

Object-Oriented Programming with JAVA: BCS306A

MODULE III

MODULE III
Contents
Inheritance
 Inheritance Basics
 Using super
 Creating a Multilevel Hierarchy
 When Constructors Are Executed
 Method Overriding
 Dynamic Method Dispatch
 Using Abstract Classes
 Using final with Inheritance
 Local Variable Type Inference and Inheritance
 The Object Class
Interfaces
 Interfaces
 Default Interface Methods
 Use static Methods in an Interface
 Private Interface Methods
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 the 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.

Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword. If we say class A extends B, means B is the superclass and A is
the extension of B.

Department of Artificial Intelligence & Data Science, DBIT

1
Object-Oriented Programming with JAVA: BCS306A
MODULE III

Demonstration of Inheritance
public class A {
int i;
int j;
void showij() {
System.out.println("i and j is " + i + " " +
j);
}

}
public class B extends A {
int k;
void showk() {
System.out.println(" The k is " + k);
}
void sum() {
System.out.println(" The sum is " + (i+j+k));
}
}
public class SimpleInheritanceDemo {

public static void main(String[] args) {


A superobj= new A(); //created a class object for A
B subobj = new B(); // created an object in the
subclass B
superobj.i=10;
superobj.j=20;
subobj.k = 30;
System.out.println("The elements of super class A is
");
superobj.showij();
// Next line of code demonstrates that the subclass
has access to all the variables defined in the superclass
//Also we can call all the functions defined in the
superclass

subobj.i=45;
subobj.j=60;
subobj.k=75;
subobj.sum();
}

Department of Artificial Intelligence & Data Science, DBIT

2
Object-Oriented Programming with JAVA: BCS306A
MODULE III

A Closer Look at the Program


 First, we have created a class A with a void showij() method inside that.
 Next, we have created an inheritance class B which is an extension of class A.
 Here class A is the superclass.
 Class B is the Subclass.
 Class B has its methods – two methods, one is showk() and another is sum()
 Next, we have created another class called SimpleInheritanceDemo to demonstrate
how the superclass and its inheritance together works
 In the InheritanceDemo class we have created the objects for both the class, that is,
the superclass, and its inheritance class
 Using the objects created for both the classes A and B we can call the methods and
assign the values to the object.

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. For Example, consider
the following simple class hierarchy.
class A {
int i;
private int j; // It is only applicable to A
void setij(int x, int y) {
i=x;
j=y;
}
}
class B extends A {
int total;
void sum() {
total= i+j; // error, since j is private for class A
}
}
public class DemoMemberAccessInheritance {
public static void main(String[] args) {
B subobj= new B();
subobj.setij(10, 15);
subobj.sum();
System.out.println("Total is "+ total);
}
/* This will throw a compilation error,
since j is private for the class A*/
}

Department of Artificial Intelligence & Data Science, DBIT

3
Object-Oriented Programming with JAVA: BCS306A
MODULE III

A Closer Look at the Program


 Here class A is the superclass
 Class B is the subclass of A
 In A we have defined the j variable as private, o it cannot be accessed by its
inheritance class.
 That is why a compilation error is observed.
 If we remove the ‘private’ keyword while defining j, the program will be executed.

A More Practical Example


Let us look at a more practical example, that will help illustrate the power of
inheritance. Here we will construct a class called Box with instance variables width, height,
and depth, and demonstrate the values assigned to the objects through parameters,
constructors, etc. Then we will create a class inheritance to include the component weight.
Hence the new class will contain a box’s width, height, depth, and weight.
public class Box {
int width;
int height;
int depth; //Three instance variables have been created
/*Box(Box obj){
//used the constructor and pass the values through an
object
width=obj.width;
height=obj.height;
depth=obj.depth;
}*/
Box(int w, int h, int d){
/*here constructor with parameters is used
to assign the object values*/
width=w;
height=h;
depth=d;
}
Box(int l){
/*Constructor to create a cube whose length,
width and depth are the same*/
width=height=depth=l;
}
int volume() {
return (width*height*depth); // To compute the volume
}
}
public class BoxWeight extends Box {

Department of Artificial Intelligence & Data Science, DBIT

4
Object-Oriented Programming with JAVA: BCS306A
MODULE III

// Here we want to include the weight of the box


int weight;
BoxWeight(int w, int h, int d, int m){
width=w;
height=h;
depth=d;
weight=m;
}
}
public class DemoBoxWeight {

public static void main(String[] args) {


BoxWeight Box1= new BoxWeight(10,20,30,40);
BoxWeight Box2= new BoxWeight(1,2,3,4);
System.out.println("The volume of my first box is "
+ Box1.volume());
System.out.println("The volume of my first box is "
+ Box2.volume());
}

}
A Closer Look at the Program
 Here we have three classes
 One class called Box.
 In the Box class we have only three instance variables width, height, and breadth
 BoxWeight class is the inheritance of the class called Box
 In BoxWeight class we have another instance variable called weight
 In the DemoBoxWeight class we can access the methods from both the Box class and
BoxWeight class.

Creating 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. As mentioned, it is preferably acceptable to use a
subclass a a superclass of other. For example, given three classes called A, B, and C, C
can be a subclass of B, which is a subclass of A. When this type of situation occurs, each
subclass inherits all the traits found in its superclasses. In this case, C inherits all aspects
of B and A.

Department of Artificial Intelligence & Data Science, DBIT

5
Object-Oriented Programming with JAVA: BCS306A
MODULE III

Demonstration of Multilevel Hierarchies


public class AAAAAA{
void callme() {
System.out.println("Inside AAAAAA'S callme method");
}
}
public class BBBBBB extends AAAAAA{
//override callme()
void callme() {
System.out.println("Inside BBBBBB'S callme method");
}
}

public class CCCCCC extends AAAAAA{


void callme() {
//override callme()
System.out.println("Inside CCCCCC'S callme method");
}
}
public class DemoDynamicMethodDispatch {

public static void main(String[] args) {


AAAAAA obja = new AAAAAA();
BBBBBB objb = new BBBBBB();
CCCCCC objc = new CCCCCC();
AAAAAA ref; // obtain a reference of type AAAAAA
ref=obja; // calls method in AAAAAA
ref.callme();
ref=objb;
ref.callme();
ref=objc;
ref.callme();

A Super Class Variable Can reference a Subclass Object


A reference variable of a superclass can be assigned a reference to any subclass
derived from that superclass. In the above example, we have created a reference to the
superclass AAAAAA by assigning the reference as ref. This ref can be used as a
reference to any subclass objects.

Department of Artificial Intelligence & Data Science, DBIT

6
Object-Oriented Programming with JAVA: BCS306A
MODULE III

Using Super
A subclass can call a constructor defined by its superclass by use of the following
form of super – super(arg – list).To see how super() is used, consider the demonstration
program on ‘Demonstration of Overriding’.

Method Overriding

If a subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java. In other words, if a subclass provides the specific
implementation of the method that has been declared by one of its parent class, it is known as
method overriding. Automatically readers will get doubt in the understanding between
overloading and overriding. The following table helps in a better understanding of these two
terms.

Overriding Overloading
Implements “runtime polymorphism” Implements “compile time polymorphism”
The method call is determined at runtime The method call is determined at compile
based on the object type time.
Occurs between superclass and subclass Occurs between the methods in the same
class.
Have the same signature (name and method Have the same name, but the parameters are
arguments) different
On error, the effect will be visible at runtime On error, it can be caught at compile time.

Demonstration of Overriding
public class A {
//Here class A (parent class) and a method called show is
created
int i, j;
A(int a, int b){
i=a;
j=b;
}
void show() {
System.out.println("i and j are " + i + " " + j);

}
}
public class B extends A{
//Here a child class B is created with a parent as A

Department of Artificial Intelligence & Data Science, DBIT

7
Object-Oriented Programming with JAVA: BCS306A
MODULE III

int k;
B(int a, int b, int c){
//Using the super keyword we are initiating the values from
the superclass
super(a,b);
k=c;
}
void show() {
super.show(); /*This will execute the methods in the
superclass.
Also, we can create the objects for class A and Perform the
task show() on class A*/

System.out.println("The value of k is "+ k);


/*Creating a method in the child class B, but the method name
show()is defined in the parent class.
But action is different*/

}
}
public class ClassOverride {

public static void main(String[] args) {


B subobj= new B(1,2,3);
A superobj=new A(1,2);//created an object for super
class A
subobj.show();
superobj.show();
}
}
A closer look at the program
 Class A is the superclass
 Class A has a method called show
 Class B is the subclass or child of A
 Class B is Accessing the values from the parent class using the super keyword
 Also class B uses the method show(), which is in Superclass A
 super.show(); will directly call the method available in the parent class A in the child
class B
 In the ClassOverride demo class, objects for the child and parent classes are created.

Department of Artificial Intelligence & Data Science, DBIT

8
Object-Oriented Programming with JAVA: BCS306A
MODULE III

Another Example of Applying a Method Overriding


Let us look at a more practical example that uses method overriding. The following
program creates a superclass called Figure and two subclasses called Rectangle and Triangle.
Each of the subclasses overrides the method called area which is in superclass Figure.

Demonstration of Program
public class Figure {
int dim1;
int dim2;
Figure(int a, int b){
dim1=a;
dim2=b;
}
int area() {
// Here just we want to demonstrate there is no action
happening in the method called area
System.out.println("The figure is undefined");
return 0;
}
}
public class Rectangle extends Figure{
Rectangle(int a, int b){
super(a, b);
}
int area() {//area() is overriding
System.out.println("Area of the rectangle is ");
return dim1 * dim2;
}

}
public class Triangle extends Figure{
Triangle(int a, int b){
//A constructor is created and values are taken from
the superclass Figure
super(a,b);
}
//overriding the area() which is defined in the superclass
Figure in the next line
int area() {
System.out.println("The area of the triangle is ");
return (dim1*dim2)/2;
}

Department of Artificial Intelligence & Data Science, DBIT

9
Object-Oriented Programming with JAVA: BCS306A
MODULE III

}
//Demonstrate how the child classes Rectangle and Triangle are
accessing the parent class Figure
public class FindArasOfAllClasses {

public static void main(String[] args) {


Figure f= new Figure(2,3);//created a superclass
object for the parent class Figure
Rectangle r = new Rectangle(6,8);
Triangle t = new Triangle(8,10);
System.out.println(f.area());
//The above code will display an undefined area
since we haven't passed any parameter
//return 0 will answer the area as 0
System.out.println(r.area());
System.out.println(r.area());

}
}
A Closer Look at the Program
 Figure is the superclass with a method area()
 The classes Rectangle and Triangle are the child Classes
 The child classes Access the instance variables defined in the parent class using the
super keyword.
 Parent class is not accepting any values, so it displays the area as 0
 The child classes are accepting the value through the constructors.

Abstraction in Java
In the Object-oriented programming paradigm, abstraction is a process of hiding the
implementation details from the user, only the needed information will be provided to the
user without exposing internal implementation details. The user will have information on
what the object does but the user will never know about how it does.

A real-life example of abstraction is car steering. As a car driver, we know that when we turn
the car steering left, the car will turn left side and when we turn the car steering right, the car
will turn right side. However, we don't know the details of how the car steering system works
internally. By defining the abstract turning behaviours of car steering, car manufacturers
abstracted the internal complexities of the steering system.

Department of Artificial Intelligence & Data Science, DBIT

10
Object-Oriented Programming with JAVA: BCS306A
MODULE III

With abstraction in place, car manufacturers can implement different steering technologies,
without changing the expected behaviours of car steering systems. As long as the car turns
right or left when the driver turns steering right or left respectively, a driver need not worry
about the internal steering technology of the car.

Abstract Classes and Methods

Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved by either using abstract classes or
interfaces. (which will be learned in the upcoming chapter).

 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.
 We cannot create objects of abstract classes in Java.

Important points about abstract classes


 An instance of an abstract class cannot be created.
 It can have abstract and non-abstract methods.
 It can have constructors and static methods.
 We can have an abstract class without any abstract method.
 If a class contains at least one abstract method then it must be declared as an abstract
class.
 Like inheritance, we can create subclasses from an abstract class using extends
keyword. A subclass object can access members of the abstract class.

Demonstration of Abstract Class

abstract class Figure {


int dim1;
int dim2;
Figure(int a, int b) {
dim1=a;
dim2=b;
}
abstract int area();
}
class Rectangle extends Figure {
Rectangle(int a, int b){
super(a,b);

Department of Artificial Intelligence & Data Science, DBIT

11
Object-Oriented Programming with JAVA: BCS306A
MODULE III

}
int area() {
//System.out.println("The area of rectangle is ");
return dim1*dim2;
}
}
class Triangle extends Figure {
Triangle(int a, int b){
super(a,b);
}
int area() {
//System.out.println("The area of Triangle is ");
return (dim1*dim2)/2;
}
}
class DemoAbstractClass {
public static void main(String[] args) {
Rectangle objectr= new Rectangle(4,7);
Triangle obectt=new Triangle(10,20);
Figure refer;
refer=objectr;
System.out.println("The area of rectangle is " +
refer.area());
refer=obectt;
System.out.println("The area of triangle is " +
refer.area());

}
}
A Closer Look at the Program
 Here we have a class called Figure which is defined as an abstract class.
 This class has only instance variables and a method called area() which does not have
a body.
 Next, we have created two inheritance classes called Rectangle and Triangle which
are inherited from the class Figure.
 The class Rectangle has accessed the instance variable from the abstract class Figure
with the help of the keyword ‘Super’.
 Also, the same method name has been called from the abstract class and created the
body of the method in the Class Rectangle.
 In the class Triangle also called the instance variables from the abstract class with the
help of super keyword.
 Also created the body of the method area().

Department of Artificial Intelligence & Data Science, DBIT

12
Object-Oriented Programming with JAVA: BCS306A
MODULE III

 In the class DemoAbstractClass we have created the objects for the classes Triangle
and Rectangle and activated the methods.

Using final with Inheritance

The final keyword is a non-access modifier used for classes, attributes, and methods,
which makes them non-changeable (impossible to inherit or override). The final keyword
is useful when you want a variable to always store the same value, like PI (3.14159...).

Using final to prevent Overriding

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

Demonstration of final to avoid overriding

class AAAA {
final void method() {
System.out.println("This cannot be overridden");
}
}
class BBB extends AAAA{
void method(); //This line is showing an error Since it
is defined as a final in the superclass
//Also, if we write the final class AAAA, then we cannot
execute the code "class BBB extends AAAA"
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
A Closer Look at the Program
 Here class AAAA has a method that is defined as the final
 The Class BBB is the inheritance of class AAAA
 Since We have defined the method() in AAAA a final when we try to use the
same in the inheritance class BBB, it will show the error message, since it will
not allow the overriding.

Using final to prevent inheritance

Department of Artificial Intelligence & Data Science, DBIT

13
Object-Oriented Programming with JAVA: BCS306A
MODULE III

Sometimes you will want to prevent a class from being inherited. To do this, precede
the class declaration with the final. Declaring a class as final implicitly declares all of its
methods as final, too. It is illegal to declare a class as abstract and final since an abstract class
is incomplete by itself and relies upon its subclasses to provide complete implementation.
Note: For implementation code please refer to the previous program.

The Object Class

There is one special class, object, defined by Java. All other classes are subclasses of
Object. That is, the Object is an upper class 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 refer to an array.

Object class is present in Java.lang package. Every class in Java is directly or


indirectly derived from the Object class. If a class does not extend any other class, then it is
a direct child class of the Object class and if extends another class then it is indirectly
derived. Therefore, the Object class methods are available to all Java classes. Hence Object
class acts as a root of the inheritance hierarchy in any Java Program. Object class defines
the following methods, which means that they are available in every object.

Using Object Class Methods


The Object class provides multiple methods which are as follows:
 tostring() method

Department of Artificial Intelligence & Data Science, DBIT

14
Object-Oriented Programming with JAVA: BCS306A
MODULE III

 hashCode() method
 equals(Object obj) method
 finalize() method
 getClass() method
 clone() method
 wait(), notify(), notifyAll() methods

toString() method
The toString() provides a String representation of an object and is used to convert an
object to a String. The default toString() method for class Object returns a string consisting
of the name of the class of which the object is an instance, the at-sign character `@’, and
the unsigned hexadecimal representation of the hash code of the object. In other words, it is
defined as:
// Default behaviour of toString() is to print class name, then
// @, then unsigned hexadecimal representation of the hash code
// of the object
public String toString()
{
return getClass().getName() + "@" +
Integer.toHexString(hashCode());
}
 It is always recommended to override the toString() method to get our String
representation of Object.
hashCode() method
For every object, JVM generates a unique number which is a hash code. It returns
distinct integers for distinct objects. A common misconception about this method is that the
hashCode() method returns the address of the object, which is not correct. It converts the
internal address of the object to an integer by using an algorithm. The hashCode() method
is native because in Java it is impossible to find the address of an object, so it uses native
languages like C/C++ to find the address of the object.

equals(Object obj) method


It compares the given object to “this” object (the object on which the method is
called). It gives a generic way to compare objects for equality. It is recommended to
override the equals(Object obj) method to get our equality condition on Objects.

Department of Artificial Intelligence & Data Science, DBIT

15
Object-Oriented Programming with JAVA: BCS306A
MODULE III

getClass() method.
It returns the class object of “this” object and is used to get the actual runtime class
of the object. It can also be used to get metadata of this class. The returned Class object is
the object that is locked by static synchronized methods of the represented class. As it is
final, we don’t override it.

finalize() method
This method is called just before an object is garbage collected. It is called
the Garbage Collector on an object when the garbage collector determines that there are no
more references to the object. We should override the finalize() method to dispose of
system resources, perform clean-up activities, and minimize memory leaks. For example,
before destroying the Servlet objects web container, always call the finalize method to
perform clean-up activities of the session.

clone() method
It returns a new object that is the same as this object .
wait(), notify(), notifyAll() methods

All these are used in Multithreading

Note: Refer to the below link for better understanding:


https://www.youtube.com/watch?v=Drmi4iJoU1o

Interfaces:
 Using the keyword interface, you can fully abstract a class’s interface from its
implementation.
 That is, using the interface, you can specify what a class must do, but not how it does
it. Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
 In practice, this means that you can define interfaces that don’t make assumptions
about how they are implemented.
 Once it 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.

Department of Artificial Intelligence & Data Science, DBIT

16
Object-Oriented Programming with JAVA: BCS306A
MODULE III

 Interfaces are designed to support dynamic method resolution at run time.


 Normally, for a method to be called from one class to another, both classes need to be
present at compile time so the Java compiler can check to ensure that the method
signatures are compatible.

Multiple Inheritance and Interface

Inheritance is one of the core concepts of Object-Oriented Programming. Multiple


Inheritance is the process in which a subclass inherits more than one superclass. Multiple
Inheritance is a feature of an object-oriented concept, where a class can inherit properties of
more than one parent class. The problem occurs when there exist methods with the same
signature in both the super classes and subclass. On calling the method, the compiler cannot
determine which class method to call and even on calling which class method gets the
priority. Java does not support Multiple Inheritance; however, Java interfaces help us achieve
Multiple Inheritance of type in Java.

Understanding the Necessity of Interface

Consider two classes , Base1 and Base2, and also consider a Derived class, which in
inheriting the properties from Base1 and Base2.

Base2
Base1
Int a=20
Int a=10

int

Derived Class

If we try to access the variable a with the help of the Derived class, ambiguity problem during
compilation (ambiguity means issues that are not defined clearly in Java language
specification.). So, an interface can be used to access multiple inheritance. Also, it is used for
abstraction, that is showing essential details, but hiding which are not known to others. If we
use interfaces, we can implement abstraction. In the interface, only the declaration of
methods is possible, but the definition of methods is hidden.

When we compare with the abstract class, the abstract class may contain abstract
methods and also normal methods, so everything will be visible to all.

Department of Artificial Intelligence & Data Science, DBIT

17
Object-Oriented Programming with JAVA: BCS306A
MODULE III

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.
 Notice that 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.
 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.

Department of Artificial Intelligence & Data Science, DBIT

18
Object-Oriented Programming with JAVA: BCS306A
MODULE III

 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 name [extends superclass] [implements interface [,interface...]] { // class-
body }
 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

Accessing Implementations Through Interface References:

 You can declare variables as object references that use an interface rather than a class
type.
 Any instance of any class that implements the declared interface can be referred to by
such a variable.
 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. This is one of the
key features of interfaces.
 The method to be executed is looked up dynamically at run time, allowing classes to
be created later than the code that calls methods on them.
 The calling code can be dispatched through an interface without having to know
anything about the “callee.

Demonstration of Implementation of interface

interface A{
int a=20;
void show();
}

interface B{
int a=25;
void show();
}
class C implements A, B
{
public int c;
public void show() {
c=A.a + B.a;

Department of Artificial Intelligence & Data Science, DBIT

19
Object-Oriented Programming with JAVA: BCS306A
MODULE III

System.out.println(c);
System.out.println(A.a);
System.out.println(B.a);
}
}
public class Test {

public static void main(String[] args) {


C obj =new C();
A ref1;
ref1=obj;
ref1.show();
/*In a similar way we can create the reference
variable
for the interface B and also generate the same output.
The below code demonstrates that*/
B ref2;
ref2=obj;
ref2.show();
}
}
A Closer Look at the Program
 Here two interfaces A and B are created.
 Both these interfaces have variables and methods, they are default public, and static.
 We can not create objects for the interfaces
 There is a class C which implements both interfaces A and B, and also class C has the
body of the method.
 Objects for class C is created in the test class.
 A reference variable ref1 and ref2 is created for the interface A and B respectively
and the class objects and the methods can be invoked through this reference variable.

Extending Interfaces in Java

Let us understand this concept with an example. Assume that you are a Java developer
and A customer named Arun needs code for addition and another customer named Anjan
needs the code for both addition and subtraction. So first we will create an interface for Arun
and keep the method name add() for Arun. Since Anjan wants both addition and subtraction,
we extend the interface that we have created for Arun. So in the new interface created for
Anjan, we create an additional method subtraction and do with the keyword extends. So that
we do not have to write the code for addition again which we have created for Arun.

Department of Artificial Intelligence & Data Science, DBIT

20
Object-Oriented Programming with JAVA: BCS306A
MODULE III

Let us understand this through the code

interface Arun {
void add();
}
interface Anjan extends Arun{
void subtract();
/*with this interface
Anjan can access both the methods add and subtract*/
}
public class Ankit implements Anjan {
public void add() {
int a=10;
int b=20;
int c;
c=a+b;
System.out.println("The sum is “ + c);
}
public void subtract() {
int a=10;
int b=20;
int c;
c=a-b;
System.out.println("The difference is “ + c);
}
}
public class TestinterfaceExample2 {
public static void main(String[] args) {
Arun ref =new Ankit();
ref.add();
Anjan ref1= new Ankit();
ref1.add();
ref1.subtract();
}
}
https://www.youtube.com/watch?v=_FrzZO2KElc – Link for understanding Extending interface
Default Methods in Interfaces
Before Java 8, we could only declare abstract methods in an interface. However, Java
8 introduced the concept of default methods. Default methods are methods that can have a

Department of Artificial Intelligence & Data Science, DBIT

21
Object-Oriented Programming with JAVA: BCS306A
MODULE III

body. The most important use of default methods in interfaces is to provide additional
functionality to a given type without breaking down the implementing classes.

Before Java 8, if a new method was introduced in an interface, then all the implementing
classes used to break. We would need to provide the implementation of that method in all the
implementing classes.

However, sometimes methods have only a 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.

Demonstration of Default Methods

public interface Vehicles {


void horn();
default void speed() {
System.out.println("The speed of vehicles");
}

}
/* Assume that a developer wants to add a method called
speed() to both the classes.
with the same implementation. So we will add default method
speed*/
public class Car implements Vehicles{
public void horn() {
System.out.println("Car Horn Sound");
}
}
public class TestVehiclesInterface {

public static void main(String[] args) {


Vehicles ref1= new Car();
ref1.horn();
ref1.speed();
Vehicles ref2= new Bike();
ref2.horn();
ref2.speed();

}
}

A Closer Look at the Program

 Interface vehicles is created first.

Department of Artificial Intelligence & Data Science, DBIT

22
Object-Oriented Programming with JAVA: BCS306A
MODULE III

 Two classes called car and Bike which will be implementing the methods available in
interface vehicles.
 Next suddenly the developer wants to add a method called speed(), which will be
implemented in all the classes.
 In this case we can define the method called speed() as a default method in the
interface with the method body, which has to be implemented in all the classes.
 Otherwise, we have to define the method Speed() in all the classes. If the number of
classes is more, typing of this method takes a longer time.
 Since we have defined the Speed() method as default we can create the objects in each
class directly.
 Also, it gives an option to change the content of the speed() method depending of the
requirements in each class.

https://www.youtube.com/watch?v=XhNeSRx0lH4

https://www.youtube.com/watch?v=KMjPrE94g44 – Default Vs Static

Use Static Methods in an Interface

Assume that in the above program the method called Speed() is common for all the classes
and objects has to be created. Then instead of the default method we can use the Static
method.

In the above program, the following code


default void speed() {
System.out.println("The speed of vehicles");
}
If we replace it with static void speed() {
System.out.println("The speed of vehicles");
}
Then the speed() can be implemented in all the classes without
defining the method body. We will be able to create the
objects for all the classes. However since we have used the
keyword static, we cannot change the action within that method.

Partial Implementations

 If a class includes an interface but does not fully implement the methods defined by
that interface, then that class must be declared as abstract.

Nested Interfaces

Department of Artificial Intelligence & Data Science, DBIT

23
Object-Oriented Programming with JAVA: BCS306A
MODULE III

 An interface can be declared a member of a class or another interface. Such an


interface is called a member interface or a nested interface.
 A nested interface can be declared as public, private, or protected.
 This differs from a top-level interface, which must either be declared as public or use
the default access level, as previously described.
 When a nested interface is used outside of its enclosing scope, it must be qualified by
the name of the class or interface of which it is a member.
 Thus, outside of the class or interface in which a nested interface is declared, its name
must be fully qualified.

Demonstration of Nested Interface

interface Arun {
void add();
}
interface Anjan extends Arun{
void subtract();
/*with this interface
Anjan can access both the methods add and subtract*/
}
public class Ankit implements Anjan {
public void add() {
int a=10;
int b=20;
int c;
c=a+b;
System.out.println("The sum is " + c);
}
public void subtract() {
int a=10;
int b=20;
int c;
c=a-b;
System.out.println("The difference is " + c);
}
}
public class TestinterfaceExample2 {
public static void main(String[] args) {
Arun ref =new Ankit();
ref.add();
Anjan ref1= new Ankit();
ref1.add();
ref1.subtract();

Department of Artificial Intelligence & Data Science, DBIT

24
Object-Oriented Programming with JAVA: BCS306A
MODULE III

}
}

A Closer Look at the Program

 An interface called Arun is created with a method called add() in that.


 Another interface called Anjan is created as an extension of the interface Arun with a
method called subtract() in that.
 The interface Anjan is having the access to both the methods add() and subtract.
 We can not create object for these interfaces.
 class called Ankit implements Anjan is created to create the body of both the methods.
 Another class TestinterfaceExample2 is created for creating the objects for this class.

Variables in Interfaces

 You can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables that are initialized to the desired values.

https://www.youtube.com/watch?v=nESVub5Pn78&t=483s - Link for Interface

https://www.youtube.com/watch?v=7w9COsroiyQ&list=PLqleLpAMfxGCtBX7KX
CSir6PnzRBukNmd&index=2 – Link for Interface

Department of Artificial Intelligence & Data Science, DBIT

25

You might also like