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

Interfaces

The document provides a comprehensive overview of interfaces in Java, detailing their purpose, syntax, and differences from classes and abstract classes. It explains key features introduced in Java 8 and 9, such as default and static methods, and addresses multiple inheritance issues. Additionally, it includes examples of interface implementation and method overriding, highlighting the rules for resolving conflicts between default methods in interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views28 pages

Interfaces

The document provides a comprehensive overview of interfaces in Java, detailing their purpose, syntax, and differences from classes and abstract classes. It explains key features introduced in Java 8 and 9, such as default and static methods, and addresses multiple inheritance issues. Additionally, it includes examples of interface implementation and method overriding, highlighting the rules for resolving conflicts between default methods in interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Interfaces

• An interface in Java is a blueprint of a class. It contain methods and


variables.

• The interface in Java is a mechanism to achieve abstraction and


multiple inheritance in java.

• There can be only abstract methods and final fields in the Java
interface, not method body.

• In other words, you can say that interfaces can have abstract methods
and variables.
• Java Interface also represents the IS-A relationship.

• It cannot be instantiated just like the abstract class.

• Since Java 8, we can have default and static methods in


an interface.

• Since Java 9, we can have private methods in an


interface.
Why use Java interface?
Syntax for defining interface

interface interfacename Interface is the keyword & interfacename is any java variable
{
variables declaration; variables can be declared as
methods declaration;
} static final type variablename = value; (variables are declared as constants)

Methods declaration will contain only a list of methods without any body
statements.

returntype methodname(parameter list)

interface item
{
static final int code = 1001;
static final string name = “fan”;
void display();
}
DIFFERENCE BETWEEN CLASS AND INTERFACE

CLASS INTERFACES
The members of a class can be constant or variables The members of an interface are always declared as
constant, i.e their values are final.

The class definition can contain the code for each of its The methods in an interface are abstract in nature. i.e
methods. i.e the methods can be abstract or non- there is no code associated with them. It is later defined
abstract. by the class that implements the interface.

It can be instantiated by declaring objects It cannot be used to declare objects.It can only be
inherited by a class.
It can use various access specifiers like public, private It can only use the public access specifier.
or protected.
Difference between abstract class and interface
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it
can have default and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.

4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract
class.

5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

6) An abstract class can extend another Java class and implement An interface can extend another Java interface only.
multiple Java interfaces.

7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword
"implements".

8) A Java abstract class can have class members like private, protected, Members of a Java interface are public by default.
etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
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.
}
IMPLEMENTING INTERFACES

interface Area
{ class Interfacetest
final static float pi = 3.14f; {
float compute (float x, float y); public static void main(String args[ ])
} {
class Rectangle implements Area Rectangle rect = new Rectangle();
{ Circle cir = new Circle();
public float compute (float x , float y) Area area; //interface object
{ area = rect; //area refers to rect object
return (x* y); System.out.println(“Area of Rectangle =” +area.compute(10,20);
} area = cir; // area refers to cir object
} System.out.println(“Area of Rectangle =” +area.compute(10,0);
class circle implements Area
{
public float compute (float x , float y)
{
return (pi*x*x);
}
}
Interface Examples
interface Drawable{
Example 1: void draw();
}
interface printable{
class Rectangle implements Drawable{
void print(); public void draw()
} {

class EX1 implements printable{ System.out.println("drawing rectangle");


}
public void print() }
{System.out.println("Hello"); class Circle implements Drawable{
} public void draw()
{
public static void main(String args[]){
System.out.println("drawing circle");}
EX1 obj = new EX1(); }
obj.print(); class TestInterface1{
public static void main(String args[]){
}
Drawable d=new Circle();
} d.draw();
Output: }}
• Hello Output :
interface Bank{ class TestInterface2{
float rateofInterest(); public static void main(String[] args)
} {
class SBI implements Bank{ Bank b=new SBI();
public float rateofInterest() System.out.println("ROI: "+b.rateofInterest()
{return 9.15;} );
} }
class PNB implements Bank{ }
public float rateofInterest() Output :
{return 9.7;} • ROI : 9.15
}
Multiple inheritance in Java by
interface
• If a class implements multiple interfaces, or an interface
extends multiple interfaces, it is known as multiple
inheritance.
Interface inheritance

• A class implements an interface, but one interface


extends another interface.
Multiple Inheritance : Examples
interface Printable{ public static void main(String args[]
void print(); ){
} test obj = new test();
interface Showable{ obj.print();
void show();
obj.show();
}
class test implements Printable,Showable{
}
public void print() }
{System.out.println("Hello");} Output :
public void show() Hello
{System.out.println("Welcome");}
• Welcome
interface Printable{ public static void main(String args[]
void print(); ){
} Test obj = new Test ();
interface Showable extends Printable{ obj.print();
void show(); obj.show();
}
}
class Test implements Showable{
}
public void print()
Output :
{System.out.println("Hello");
Hello
}
Welcome
public void show(){System.out.println("Welcome");
}
Java 8 Default Method in Interface

• Since Java 8, we can have method body in interface. But


we need to make it default method.
• The default methods in the interface are defined with the
default keyword.
2. You can call a default method of the interface from the class
that provides the implementation of the interface.

Syntax: To define a default method in the interface, we must use


the “default” keyword with the method signature.
syntax

interface MyInterface {
void existingMethod();// abstract method with no body

default void newDefaultMethod() // default keyword , method is defined


{
System.out.println("This is a default method.");
}
}
Default Method in Interface :
class TestInterfaceDefault{
interface Drawable{ public static void main(String args[])
void draw(); {
default void msg() Drawable d=new Rectangle();
{ d.draw();
System.out.println("default method"); d.msg();
} }
} }
class Rectangle implements Drawable{
public void draw() Output:
{ drawing rectangle
System.out.println("drawing rectangle");} default method

}
Default Method in Interface :
If a class implements an interface that has a default method, the class can choose to:
- Use the default version of the method, or
- Provide its own version (i.e., override it).

interface MyInterface { public class Test {


default void show() //default method public static void main(String[] args)
{ {
System.out.println("Default show() MyInterface obj = new MyClass();
from interface"); obj.show();
} }
} }
class MyClass implements MyInterface
//override method
{ Output:
public void show() {
System.out.println("Overridden Overridden show() in MyClass
show() in MyClass");
}}
Without Default (Pre-Java 8):
With Default (Java 8+):
interface Animal {
interface Animal {
void makeSound();
void makeSound();
void sleep();
default void sleep() {
}
System.out.println("Sleeping...");
class Dog implements Animal {
}
public void makeSound() {
}
System.out.println("Bark!");
→ Existing classes remain unaffected
}
→ Can override if needed
// add sleep() method here
}

→ All classes must implement both methods


→ Adding sleep() later breaks existing code
Java 8 Static Method in Interface

• Since Java 8, we can have static method in interface.


• Static method in Interface
• 1. The static methods in Interface are defined with the
static keyword.
2. You can define static default methods in the interface. The
static method will be available for all instances of the class that
implements the interface.
• Syntax: To define a static default method in the interface, we
must use the “static” keyword with the method signature.
Static Method in Interface: In Java 8 we can have static method in interface.

class test{
interface Find{
public static void main(String args[]){
void show(); //abstract method
Find f=new test();
static int cube(int x)
f.show();
{
System.out.println(Find.cube(3));
return x*x*x;
}
}
}
}
class test implements Find{ Output :
public void show() computing cube
{
System.out.println(”computing cube"); 27
} Note : Find is the Interface name
}
Static Method in Interface: Why

1. Grouping utility methods with the interface


Instead of putting them in separate helper classes, you can keep them in the interface itself.
2. No need for implementation by classes
Classes that implement the interface do not inherit the static methods, so there’s no risk of conflicts.
3. Cleaner API design
It keeps your code organized and improves readability.
interface MathUtils {
static int cube(int x) {
return x * x * x;
}
Note:
}
 You call the method using
InterfaceName.methodName()
public class Test {
public static void main(String[] args) {
 Implementing classes cannot override static methods.
int result = MathUtils.cube(3);
System.out.println(result); // Output: 27
}
}
Multiple inheritance issues in java

• Assume two interfaces called Alpha and Beta are implemented by a


class called MyClass.
• What happens if both Alpha and Beta provide a method called reset
for which both declare a default implementations?
• Is the version by Alpha or the version by Beta used by
Myclass?//ambiguity
• Or Consider a situation in which Beta extends Alpha. Which version of
default method is used?
• What if Myclass provides its own implementation of the method?
• Java defines a set of rules that resolves such conflicts
i) in all cases ,a class implementation takes prioroity over an interface implementation
if Myclass provides an override of the reset() default method ,Myclass version is used.

ii)In cases in which a class implements two interfaces that both have same default
method,but the class does not override that method,then an error will result.

iii) In cases in which one interface inherits another,with both defining a common default
method,the inheriting interface’s version of the method takes precedence.

iv) It is possible to explicitly refer to adefault implementation in an inherited interface by


using a new
form of super.
InterfaceNamesuper.methodname();

You might also like