Chapter 3.3
Chapter 3.3
Mr. R. M. Patil
SY CO, JPR
2023-2024
3.3. Interface in Java
An interface in Java is a blueprint of a class. It has 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 method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have
abstract methods and variables. It cannot have a method
body.
3.3. Interface in Java
Why use Java interface?
3.3. Interface in Java
How to declare an interface?
An interface is declared by using the interface keyword.
It provides total abstraction; means all the methods in an interface
are declared with the empty body, and all the fields are public, static
and final by default.
A class that implements an interface must implement all the
methods declared in the interface.
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
3.3. Interface in Java
3.3. Interface in Java
As shown in the figure given below, a class extends
another class, an interface extends another interface, but
a class implements an interface.
3.3. Interface in Java Java Interface Example:
interface print
{
void show();
}
class demo implements print
{
public void show()
{
System.out.println("Hello");
}
public static void main(String args[])
{
demo d = new demo();
d.show();
}
}
3.3. Interface in Java Java Interface Example: (Multiple Inheritance)
interface first
{
public void dispaly();
}
interface second
class test
{
{
public void show(); public static void main(String[] args)
} {
class Demo implements first, second Demo d = new Demo();
{ d.display();
public void display() d.show();
{ }
System.out.println("Some text.."); }
}
public void show()
{
System.out.println("Some other text...");
}
}
3.3. Interface in Java – Extending Interface-Hybrid Inheritance
While inheriting an interface through another interface
“extends” keyword is used.
class demo
{
public static void main(String args[])
{
D d1 = new D();
d1.display1();
d1.display2();
d1.display3();
}
}
3.3. Interface in Java – Interface Reference
Example:
interface area
void calc();
class demo class circle implements area class triangle implements area
void calc(){….} void calc(){….}
{
public static void main(String args[])
{
area a;
a = new circle();
a.calc(); //Call to circle class method
a = new triangle();
a.calc(); //Call to triangle class method
}
}
3.3. Interface in Java –Nested Interface
class : gross_salary
TA, DA, HRA
total_sal()
Homework
4. Write a java program to extend interface assuming suitable data. S18 - 6M