implements
Learn implements step by step with clear examples and exercises.
Title: Mastering Java's implements Keyword - A full guide
Why This Matters
In this tutorial, we will delve into the implements keyword in Java, a crucial concept for creating interfaces and implementing them to extend the functionality of classes. Understanding this topic is essential for developing robust and flexible applications, as well as preparing for job interviews and real-world coding challenges.
An interface in Java serves as a contract or blueprint that defines a set of methods and constants that a class must implement to conform to the interface's behavior. By using interfaces, we can achieve greater code reusability, flexibility, and maintainability in our applications.
Prerequisites
Before diving into the implements keyword, it's important to have a solid understanding of the following topics:
- Basic Java syntax and structure
- Classes and objects
- Methods and function overloading
- Variables and data types
- Control structures (if-else, loops)
- Exception handling
- Understand what an interface is, its purpose, and how it differs from a class
- Learn about the properties of interfaces, such as all methods being abstract by default and no instance of an interface can be created
Core Concept
Defining an Interface
An interface in Java is a collection of abstract methods and constants that define a set of rules or behaviors for a class to follow. A class can implement multiple interfaces, but it must provide concrete implementations for all the abstract methods defined within those interfaces.
interface MyInterface {
public abstract void myMethod(); // An abstract method in an interface
int MY_CONSTANT = 10; // A constant in an interface
}
Implementing an Interface
To implement an interface, a class must declare that it implements the interface and provide concrete implementations for all its abstract methods.
public class MyClass implements MyInterface {
public void myMethod() {
// Concrete implementation of the abstract method
}
}
Accessing Interface Methods in Implemented Classes
Once a class has implemented an interface, it can access and call its methods just like any other method.
public class Main {
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.myMethod(); // Calling the method from the implemented interface
}
}
Interfaces and Polymorphism
Interfaces play a significant role in polymorphism, allowing objects of different classes to be treated as if they were instances of a single class that implements the shared interface. This enables greater flexibility and code reusability.
Polymorphism Example
Let's create an example where we define an interface Shape with methods for calculating area and perimeter, and then implement this interface in two classes: Circle and Rectangle. We will also create a method calculateTotalArea that takes an array of shapes and calculates their total area.
interface Shape {
double PI = 3.14; // A constant in the interface
public abstract double getArea(); // An abstract method in the interface
public abstract double getPerimeter(); // Another abstract method in the interface
}
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return PI * Math.pow(radius, 2); // Concrete implementation of the abstract method
}
@Override
public double getPerimeter() {
return 2 * PI * radius; // Concrete implementation of the abstract method
}
}
public class Rectangle implements Shape {
private int width, height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height; // Concrete implementation of the abstract method
}
@Override
public double getPerimeter() {
return 2 * (width + height); // Concrete implementation of the abstract method
}
}
Now, we can create objects of both classes, store them in an array, and call a method that calculates their total area.
public class Main {
public static void main(String[] args) {
Shape[] shapes = new Shape[2];
shapes[0] = new Circle(5);
shapes[1] = new Rectangle(4, 6);
double totalArea = calculateTotalArea(shapes);
System.out.println("Total area: " + totalArea); // Output: Total area: 78.53981633974483
}
public static double calculateTotalArea(Shape[] shapes) {
double totalArea = 0;
for (Shape shape : shapes) {
totalArea += shape.getArea();
}
return totalArea;
}
}
Worked Example
Creating a Simple Interface and Implementing Classes
Let's create an interface Printable with a method for printing, then implement this interface in two classes: Printer and Console. We will also create a method printAll that takes an array of printable objects and prints them all.
interface Printable {
void print(); // An abstract method in the interface
}
class Printer implements Printable {
private String printerName;
public Printer(String printerName) {
this.printerName = printerName;
}
@Override
public void print() {
System.out.println("Printing from " + printerName);
}
}
class Console implements Printable {
@Override
public void print() {
System.out.println("Printing to console");
}
}
Now, we can create objects of both classes, store them in an array, and call a method that prints all the printable objects.
public class Main {
public static void main(String[] args) {
Printable[] printables = new Printable[2];
printables[0] = new Printer("HP LaserJet");
printables[1] = new Console();
printAll(printables);
}
public static void printAll(Printable[] printables) {
for (Printable printable : printables) {
printable.print();
}
}
}
When you run the Main class, it will output:
Printing from HP LaserJet
Printing to console
Common Mistakes
- Forgetting to define an abstract method in the interface: All methods in an interface must be abstract, or they will cause a compile-time error when trying to implement the interface.
- Not providing concrete implementations for all abstract methods in the implementing class: A class that implements an interface must provide concrete implementations for all its abstract methods. Otherwise, it won't compile successfully.
- Invoking methods from an interface without creating an instance of a class that implements the interface: An interface doesn't have state or behavior by itself; you need to create an object of a class that implements the interface to call its methods.
- ### Mistakes when using interfaces in inheritance
- Not understanding the difference between interfaces and abstract classes: Interfaces are used for multiple inheritance, while abstract classes can have instance variables and concrete methods.
- Forgetting to override all abstract methods from a superclass when creating a subclass that implements an interface: If a class inherits from an abstract class and implements an interface, it must provide concrete implementations for all the methods in both the superclass and the interface.
Practice Questions
- Create an interface
Vehiclewith methods for calculating speed and distance traveled, then implement this interface in two classes:CarandBike.
- Given the following interface, create a class that implements it:
interface Printable {
public void print();
}
- Create an abstract class
Animalwith methods for eating and sleeping, then define an interfaceFlyablewith a method for flying. Now, create a classBirdthat extendsAnimaland implementsFlyable. Provide concrete implementations for all the methods in both the superclass and the interface.
FAQ
- Can a class implement multiple interfaces? Yes, a class can implement multiple interfaces in Java.
- What happens if a class implements an interface but doesn't provide concrete implementations for all its abstract methods? The class won't compile successfully; you must provide concrete implementations for all abstract methods defined within the implemented interfaces.
- Can I create an object of an interface directly? No, you cannot create an object of an interface directly in Java. Instead, you need to create an instance of a class that implements the interface.
- ### FAQ about using interfaces in inheritance
- What is multiple inheritance in Java? Multiple inheritance refers to a class inheriting from more than one superclass or implementing more than one interface. However, in Java, multiple implementation of interfaces is allowed, but multiple inheritance of classes is not supported directly (except for certain cases with interfaces).
- Why can't I extend two classes directly in Java? Direct multiple inheritance from classes leads to the "Diamond Problem," where a subclass inherits duplicate methods from its superclasses, causing ambiguity about which method implementation to use. To avoid this issue, Java does not support direct multiple inheritance from classes but allows multiple implementation of interfaces instead.