In Java, abstract classes and interfaces are used to define common behavior for a group of classes. Both abstract classes and interfaces cannot be instantiated, and they define a set of methods that must be implemented by their subclasses. Here are some basics of abstract classes and interfaces in Java:
1. Abstract classes: An abstract class is a class that is declared with the `abstract` keyword and cannot be instantiated. Abstract classes can contain both abstract and non-abstract methods. Abstract methods are declared without a body and must be implemented by their concrete subclasses. For example:
public abstract class Shape { public abstract double area(); } public class Rectangle extends Shape { private double width; private double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } public double area() { return width * height; } }
Here, the `Shape` class is an abstract class that declares an abstract method `area()`. The `Rectangle` class extends the `Shape` class and implements the `area()` method.
2. Interfaces: An interface is a collection of abstract methods that can be implemented by any class. Unlike abstract classes, interfaces cannot contain any non-abstract methods or variables. Classes that implement an interface must provide an implementation for all of its methods. For example:
public interface Printable { void print(); } public class Document implements Printable { public void print() { System.out.println("Printing document..."); } }
Here, the `Printable` interface declares a single method `print()`. The `Document` class implements the `Printable` interface and provides its own implementation for the `print()` method.
3. Differences between abstract classes and interfaces: Abstract classes and interfaces have some differences in their usage and implementation. Here are some of the key differences:
– An abstract class can contain both abstract and non-abstract methods, while an interface can only contain abstract methods.
– A class can only extend one abstract class, but it can implement multiple interfaces.
– An abstract class can have constructor and instance variables, while an interface cannot have either.
– An abstract class can provide a default implementation for some or all of its methods, but an interface cannot provide any implementation.
Abstract classes and interfaces are important concepts in Java, and they provide a way to define common behavior for a group of classes. By using abstract classes and interfaces, you can write more modular and reusable code that can be easily extended and customized.