0% found this document useful (0 votes)
2 views

interfaces in java

In Java, an interface is a reference type that defines a contract for classes to implement, containing abstract methods, default methods, static methods, and constants. Interfaces support multiple inheritance and allow for loose coupling between classes, enabling polymorphism and decoupling code. Key differences between classes and interfaces include the ability to instantiate classes, support for multiple inheritance, and the presence of constructors in classes but not in interfaces.

Uploaded by

gyashika198
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

interfaces in java

In Java, an interface is a reference type that defines a contract for classes to implement, containing abstract methods, default methods, static methods, and constants. Interfaces support multiple inheritance and allow for loose coupling between classes, enabling polymorphism and decoupling code. Key differences between classes and interfaces include the ability to instantiate classes, support for multiple inheritance, and the presence of constructors in classes but not in interfaces.

Uploaded by

gyashika198
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

In Java, an interface is a reference type, similar to a class, that can contain only constants,

method signatures, default methods, static methods, and nested types. Interfaces cannot have
instance variables or constructors. They are used to represent a contract or a blueprint that
other classes can implement.

Key Characteristics of Interfaces:

1. Abstract Methods: An interface can contain methods that do not have a body. These
methods must be implemented by the class that implements the interface.

interface Animal {
void sound(); // Abstract method
}

2. Default Methods: Since Java 8, interfaces can also have default methods, which have
a body. These methods provide default behavior that classes can inherit, but they can
be overridden if needed.

interface Animal {
default void sleep() {
System.out.println("Animal is sleeping.");
}
}

3. Static Methods: Interfaces can also contain static methods that belong to the interface
itself, not to instances of implementing classes.

interface Animal {
static void move() {
System.out.println("Moving...");
}
}

4. Constants: All variables declared in an interface are implicitly public, static, and final
(i.e., constants). They must be initialized when declared.

interface Animal {
int MAX_AGE = 100; // Constant
}

Implementing an Interface:

A class that implements an interface must provide implementations for all of its abstract
methods, unless the class is abstract. A class can implement multiple interfaces, allowing for
multiple inheritances of behaviors (but not state).

interface Animal {
void sound();
}
interface Swimmer {
void swim();
}

class Dolphin implements Animal, Swimmer {


public void sound() {
System.out.println("Dolphin sound");
}

public void swim() {


System.out.println("Dolphin swimming");
}
}

Explanation of the Example:

 Interfaces Declaration:
o Animal and Swimmer are interfaces, each declaring one method: sound() and
swim(), respectively.
 Class Implementation:
o Dolphin is a class that implements both Animal and Swimmer interfaces.
o It provides concrete implementations for the sound() and swim() methods.
 Usage:

public class Main {


public static void main(String[] args) {
Dolphin dolphin = new Dolphin();
dolphin.sound(); // Outputs: Dolphin sound
dolphin.swim(); // Outputs: Dolphin swimming
}
}

In the Main class, we create an instance of Dolphin and call its sound() and swim() methods,
demonstrating polymorphism.

Advantages of Using Interfaces:

 Decoupling Code: Interfaces allow classes to interact with each other without
knowing about their internal implementations.
 Polymorphism: You can use objects of different classes in a similar way if they
implement the same interface.
 Multiple Inheritance: Since Java doesn't support multiple inheritance with classes,
interfaces allow a class to inherit behavior from multiple sources.

Class vs Interface

 The following table lists all the major differences between an interface and a
class in Java.
Features Class Interface

The keyword used to create a The keyword used to create an


Keyword class is “class”. interface is “interface”.

A class can be instantiated i.e., The keyword used to create an


Instantiation objects of a class can be created. interface is “interface”

Classes do not support multiple Interface supports multiple


Inheritance inheritance. inheritance.

A class can implement an interface


A class can inherit another class using the keyword “implements”.
Inheritance using the keyword extends. An interface can inherit another
Mechanism interface using “extends”.

Constructors It can contain constructors. It cannot contain constructors.

An interface contains abstract


Methods in a class can be methods by default (before Java 8)
abstract, concrete, or both. or default/static methods (from
Methods Java 8 onward).

Variables and methods in a class


can be declared using any access All variables and methods in an
Access specifier(public, private, default, interface are declared as public
Specifiers protected).

Variables in a class can be


All variables are static and final.
Variables static, final, or neither.

An interface specifies a contract for


A class is a blueprint for
classes to implement by focusing
creating objects and
on capabilities rather than
encapsulates data and behavior.
Purpose implementation.
Here are a few more examples to demonstrate different use cases of interfaces in Java. These
examples show how interfaces can be used in different contexts, such as in the
implementation of multiple interfaces, providing default methods, and achieving loose
coupling.

1. Using Multiple Interfaces (Multiple Inheritance)

In Java, a class can implement more than one interface. This is one way Java supports
multiple inheritance, which is not directly supported by classes.

interface Animal {
void sound();
}

interface AnimalBehavior {
void sleep();
}

class Dog implements Animal, AnimalBehavior {


@Override
public void sound() {
System.out.println("Bark");
}

@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Bark
dog.sleep(); // Output: Dog is sleeping
}
}

2. Default Methods in Interfaces

Default methods allow you to add functionality to interfaces without breaking the existing
implementations of classes. This is helpful when you want to add new methods to an
interface but don’t want to force all existing classes to implement those methods.

interface Vehicle {
void move();

// Default method
default void stop() {
System.out.println("Vehicle is stopping...");
}
}

class Car implements Vehicle {


@Override
public void move() {
System.out.println("Car is moving");
}
}

public class Main {


public static void main(String[] args) {
Car car = new Car();
car.move(); // Output: Car is moving
car.stop(); // Output: Vehicle is stopping...
}
}

In this example, the stop method is defined as a default method in the interface Vehicle, so the
Car class doesn't have to implement it. The Car class only implements the move method.

3. Static Methods in Interfaces

Interfaces can also contain static methods. These methods belong to the interface itself, not to
instances of implementing classes.

interface MathOperations {
static int add(int a, int b) {
return a + b;
}

static int multiply(int a, int b) {


return a * b;
}
}

public class Main {


public static void main(String[] args) {
// Static methods are called on the interface itself
System.out.println(MathOperations.add(5, 3)); // Output: 8
System.out.println(MathOperations.multiply(5, 3)); // Output: 15
}
}

4. Interfaces as Types for Loose Coupling

One of the primary benefits of interfaces is that they allow you to create more flexible and
loosely-coupled code. You can use interfaces as types to allow different classes to interact
without being tightly bound to a particular implementation.

interface Payment {
void processPayment();
}

class CreditCardPayment implements Payment {


@Override
public void processPayment() {
System.out.println("Processing credit card payment");
}
}
class PayPalPayment implements Payment {
@Override
public void processPayment() {
System.out.println("Processing PayPal payment");
}
}

public class Main {


public static void main(String[] args) {
// Loose coupling, Payment is just an interface type
Payment payment = new CreditCardPayment();
payment.processPayment(); // Output: Processing credit card payment

payment = new PayPalPayment();


payment.processPayment(); // Output: Processing PayPal payment
}
}

In this example, the Payment interface is used as a type to represent different payment
methods. This allows the client code (the Main class) to process payments without knowing
the specific implementation (whether it's CreditCardPayment or PayPalPayment).

You might also like