Introduction
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 contain instance fields or constructors. They are used to specify a set of methods that a class must implement.
Key Concepts
- Definition: An interface is defined using the
interfacekeyword. - Implementation: A class implements an interface using the
implementskeyword. - Multiple Inheritance: A class can implement multiple interfaces.
- Abstract Methods: All methods in an interface are abstract by default (until Java 8).
- Default Methods: From Java 8, interfaces can have default methods with a body.
- Static Methods: From Java 8, interfaces can also have static methods.
- Constants: All fields in an interface are implicitly
public,static, andfinal.
Defining an Interface
// Define an interface
public interface Animal {
// Abstract method (no body)
void eat();
// Default method
default void sleep() {
System.out.println("Sleeping...");
}
// Static method
static void breathe() {
System.out.println("Breathing...");
}
}Explanation
void eat();: This is an abstract method. Any class that implements theAnimalinterface must provide an implementation for this method.default void sleep(): This is a default method. It provides a default implementation that can be overridden by implementing classes.static void breathe(): This is a static method. It can be called on the interface itself, not on instances of the implementing classes.
Implementing an Interface
// Implementing the interface
public class Dog implements Animal {
// Provide implementation for the abstract method
@Override
public void eat() {
System.out.println("Dog is eating...");
}
// Optionally override the default method
@Override
public void sleep() {
System.out.println("Dog is sleeping...");
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: Dog is eating...
dog.sleep(); // Output: Dog is sleeping...
Animal.breathe(); // Output: Breathing...
}
}Explanation
Dogclass implements theAnimalinterface.- The
eatmethod is overridden to provide a specific implementation. - The
sleepmethod is also overridden, although it is optional since it has a default implementation in the interface. - The
breathemethod is called on theAnimalinterface directly.
Multiple Interfaces
// Define another interface
public interface Pet {
void play();
}
// Implementing multiple interfaces
public class Cat implements Animal, Pet {
@Override
public void eat() {
System.out.println("Cat is eating...");
}
@Override
public void play() {
System.out.println("Cat is playing...");
}
public static void main(String[] args) {
Cat cat = new Cat();
cat.eat(); // Output: Cat is eating...
cat.play(); // Output: Cat is playing...
Animal.breathe(); // Output: Breathing...
}
}Explanation
Catclass implements bothAnimalandPetinterfaces.- It provides implementations for the
eatmethod fromAnimaland theplaymethod fromPet.
Practical Exercise
Exercise
-
Define an interface
Vehiclewith the following methods:void start()void stop()default void honk(): Print "Honking..."static void service(): Print "Vehicle service required."
-
Create a class
Carthat implements theVehicleinterface. Provide implementations for thestartandstopmethods. -
In the
mainmethod of theCarclass, create an instance ofCarand call all the methods defined in theVehicleinterface.
Solution
// Define the Vehicle interface
public interface Vehicle {
void start();
void stop();
default void honk() {
System.out.println("Honking...");
}
static void service() {
System.out.println("Vehicle service required.");
}
}
// Implement the Vehicle interface
public class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car is starting...");
}
@Override
public void stop() {
System.out.println("Car is stopping...");
}
public static void main(String[] args) {
Car car = new Car();
car.start(); // Output: Car is starting...
car.stop(); // Output: Car is stopping...
car.honk(); // Output: Honking...
Vehicle.service(); // Output: Vehicle service required.
}
}Explanation
- The
Vehicleinterface is defined with abstract methodsstartandstop, a default methodhonk, and a static methodservice. - The
Carclass implements theVehicleinterface and provides implementations for thestartandstopmethods. - In the
mainmethod, an instance ofCaris created, and all the methods from theVehicleinterface are called.
Conclusion
In this section, we learned about interfaces in Java, how to define them, and how to implement them in classes. We also explored the concepts of default and static methods in interfaces, and how a class can implement multiple interfaces. This knowledge is fundamental for understanding Java's approach to abstraction and polymorphism, which are key principles of object-oriented programming.
Java Programming Course
Module 1: Introduction to Java
- Introduction to Java
- Setting Up the Development Environment
- Basic Syntax and Structure
- Variables and Data Types
- Operators
Module 2: Control Flow
Module 3: Object-Oriented Programming
- Introduction to OOP
- Classes and Objects
- Methods
- Constructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced Object-Oriented Programming
Module 5: Data Structures and Collections
Module 6: Exception Handling
Module 7: File I/O
Module 8: Multithreading and Concurrency
- Introduction to Multithreading
- Creating Threads
- Thread Lifecycle
- Synchronization
- Concurrency Utilities
Module 9: Networking
- Introduction to Networking
- Sockets
- ServerSocket
- DatagramSocket and DatagramPacket
- URL and HttpURLConnection
