Interfaces and abstract classes are the essential components for achieving abstraction and polymorphism.
What are Interfaces?
An interface in Java is a reference type, similar to a class, that can contain only abstract methods, static methods, default methods, and static final variables (constants). Interfaces are used to achieve abstraction and multiple inheritance in Java. Interfaces may not be directly instantiated.
πBefore Java 8, interfaces could have only abstract methods.
The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface.
πTo overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.
Default methods can be overridden by implementing classes if necessary.
Key Features of Interfaces
-
Abstract Methods: Methods without a body, declared using the
abstract
keyword. - Default Methods: Methods with a body, introduced in Java 8, allowing interfaces to provide default implementations.
- Static Methods: Methods that belong to the interface itself, not to instances of the interface.
-
Constants: Variables declared as
static
andfinal
, which are implicitly public.
What are Abstract Classes?
An abstract class in Java is a class that cannot be instantiated on its own and may contain abstract methods (methods without a body) and concrete methods (methods with a body). Abstract classes are used to provide a common base for subclasses, allowing for code reuse and the definition of shared behavior.
Key Features of Abstract Classes
-
Abstract Methods: Methods without a body, declared using the
abstract
keyword. - Concrete Methods: Methods with a body, providing default implementations.
- Constructors: Abstract classes can have constructors, but they cannot be instantiated directly.
- Instance Variables: Abstract classes can have instance variables and static variables.
Differences Between Interfaces and Abstract Classes
Multiple Inheritance
- Interfaces: Java supports multiple inheritance through interfaces, allowing a class to implement multiple interfaces.
- Abstract Classes: Java does not support multiple inheritance of classes, meaning a class can extend only one abstract class.
Method Bodies
- Interfaces: Prior to Java 8, interfaces could not contain method bodies. With Java 8, default and static methods can have bodies.
- Abstract Classes: Abstract classes can contain both abstract methods (without bodies) and concrete methods (with bodies).
Variables
-
Interfaces: Variables in interfaces are implicitly
public
,static
, andfinal
. - Abstract Classes: Abstract classes can have instance variables, static variables, and constants.
Usage
- Interfaces: Ideal for defining contracts that multiple classes can implement.
- Abstract Classes: Suitable for providing a common base for a family of related classes, sharing code and behavior.
Java's Approach to Inheritance
Java supports only single inheritance, meaning each class can inherit fields and methods of only one class. If you need to inherit properties from more than one source, Java provides the concept of interfaces, which is a form of multiple inheritance.
πInterfaces are similar to classes. However, they define only the signature of the methods and not their implementations. The methods that are declared in the interface are implemented in the classes. Multiple inheritance occurs when a class implements multiple interfaces.
In Java, multiple inheritance is achieved through interfaces rather than classes. This allows a class to implement multiple interfaces, inheriting the method signatures from each of them. Below is an example demonstrating multiple inheritance using interfaces.
Example of Multiple Inheritance Using Interfaces
Let's define two interfaces, Flyable
and Swimmable
, and a class Duck
that implements both interfaces.
Interface: Flyable
public interface Flyable {
void fly();
}
Interface: Swimmable
public interface Swimmable {
void swim();
}
Class: Duck
public class Duck implements Flyable, Swimmable {
@Override
public void fly() {
System.out.println("Duck is flying");
}
@Override
public void swim() {
System.out.println("Duck is swimming");
}
public static void main(String[] args) {
Duck duck = new Duck();
duck.fly();
duck.swim();
}
}
Explanation
-
Interfaces:
-
Flyable
interface defines a methodfly()
. -
Swimmable
interface defines a methodswim()
.
-
-
Class:
-
Duck
class implements bothFlyable
andSwimmable
interfaces. - The
Duck
class provides implementations for bothfly()
andswim()
methods.
-
-
Main Method:
- An instance of
Duck
is created. - The
fly()
andswim()
methods are called on theDuck
instance, demonstrating that theDuck
class has inherited behavior from both interfaces.
- An instance of
Output
Duck is flying
Duck is swimming
Here's a simple diagram to illustrate the relationship:
+----------------+
| Flyable |<--------------->Interface
|----------------|
| + fly() |
+----------------+
^
|
| Implements
|
+----------------+
| Duck |<--------------->Class
|----------------|
| + fly() |
| + swim() |
+----------------+
^
|
| Implements
|
+----------------+
| Swimmable |<--------------->Interface
|----------------|
| + swim() |
+----------------+
In this example, the Duck
class demonstrates multiple inheritance by implementing both the Flyable
and Swimmable
interfaces. This allows the Duck
class to inherit and provide implementations for the methods defined in both interfaces, showcasing how Java achieves multiple inheritance through interfaces.
Abstract Class in Java
Abstract classes in Java are used to provide a common base for a family of related classes. They can contain both abstract methods (methods without a body) and concrete methods (methods with a body). Below is an example demonstrating the use of an abstract class.
Example of an Abstract Class
Let's define an abstract class Animal
and two subclasses Dog
and Cat
that extend the Animal
class.
Abstract Class: Animal
public abstract class Animal {
// Abstract method (does not have a body)
public abstract void makeSound();
// Concrete method (has a body)
public void sleep() {
System.out.println("The animal is sleeping");
}
}
Subclass: Dog
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog says: Woof!");
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
dog.sleep();
}
}
Subclass: Cat
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat says: Meow!");
}
public static void main(String[] args) {
Cat cat = new Cat();
cat.makeSound();
cat.sleep();
}
}
Explanation
-
Abstract Class: Animal
- The
Animal
class is declared asabstract
, meaning it cannot be instantiated directly. - It contains an abstract method
makeSound()
, which must be implemented by any subclass. - It also contains a concrete method
sleep()
, which provides a default implementation.
- The
-
Subclass: Dog
- The
Dog
class extends theAnimal
class. - It provides an implementation for the abstract method
makeSound()
. - The
main
method creates an instance ofDog
and calls themakeSound()
andsleep()
methods.
- The
-
Subclass: Cat
- The
Cat
class extends theAnimal
class. - It provides an implementation for the abstract method
makeSound()
. - The
main
method creates an instance ofCat
and calls themakeSound()
andsleep()
methods.
- The
Output
For the Dog
class:
Dog says: Woof!
The animal is sleeping
For the Cat
class:
Cat says: Meow!
The animal is sleeping
Here's a simple diagram to illustrate the relationship:
+----------------+
| Animal |
|----------------|
| + makeSound() |<-----------+
| + sleep() | |
+----------------+ |
^ | Extends
| |
| Extends |
| |
+----------------+ +----------------+
| Dog(class) | | Cat(class) |
|----------------| |----------------|
| + makeSound() | | + makeSound() |
+----------------+ +----------------+
In this example, the Animal
abstract class provides a common base for the Dog
and Cat
subclasses. The Animal
class defines an abstract method makeSound()
that must be implemented by any subclass, and a concrete method sleep()
that provides a default implementation. The Dog
and Cat
classes extend the Animal
class and provide their own implementations of the makeSound()
method.
Key Points About Interfaces
- Abstraction: The interface in Java is a mechanism to achieve abstraction.
- Default Methods: By default, interface methods are abstract and public.
-
Method Types: Interface methods can be only
public
,private
,abstract
,default
,static
, andstrictfp
. -
Field Types: Interface fields (variables) can be only
public
,static
, orfinal
. - IS-A Relationship: Java Interface also represents the IS-A relationship.
- Instantiation: It cannot be directly instantiated, just like the abstract class.
- Loose Coupling: It can be used to achieve loose coupling.
-
Implicitly Abstract: Every interface is implicitly
abstract
. -
Default Methods:
default
methods are allowed only in interfaces.
interface Colorable {
void setColor(byte r, byte g, byte b);
}
class Point { int x, y; }
class ColoredPoint extends Point implements Colorable {
byte r, g, b;
public void setColor(byte rv, byte gv, byte bv) {
r = rv; g = gv; b = bv;
}
}
class Test {
public static void main(String[] args) {
Point p = new Point();
ColoredPoint cp = new ColoredPoint();
p = cp;
Colorable c = cp; β
// interface object assigned indirectly
}
}
Practical Applications
Using Interfaces
Interfaces are commonly used to define APIs, frameworks, and libraries. For example, the java.util.List
interface provides a contract for list implementations, such as ArrayList
and LinkedList
.
public interface List<E> extends Collection<E> {
boolean add(E e);
E get(int index);
// Other methods...
}
Using Abstract Classes
Abstract classes are often used to provide a base class for a family of related classes. For example, the java.util.AbstractList
class provides a skeletal implementation of the List
interface, reducing the amount of code that subclasses need to implement.
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
protected AbstractList() {}
public boolean add(E e) {
add(size(), e);
return true;
}
// Other methods...
}
Difference Between Interface and Abstract class
SNo | Interface | Abstract Class |
---|---|---|
1 | Interfaces cannot be instantiated | Abstract classes cannot be instantiated |
2 | It can have both abstract and non-abstract methods | It can have both abstract and non-abstract methods |
3 | In interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public | In abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods |
4 | Interface supports multiple inheritance. Multiple interfaces can be implemented | Abstract class or class can extend only one class |
5 | It is used if you expect that unrelated classes would implement your interface. Eg, the interfaces Comparable and Cloneable are implemented by many unrelated classes | It is used if you want to share code among several closely related classes |
6 | It is used if you want to specify the behavior of a particular data type, but not concerned about who implements its behavior. | It is used if you expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private) |
Ref: https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.
Expert Opinions
According to Joshua Bloch, author of "Effective Java," interfaces are preferred over abstract classes for defining types because they are more flexible and support multiple inheritance. However, abstract classes are useful for providing shared functionality and reducing code duplication.
"Interfaces are ideal for defining mixins. Classes, by contrast, are ideal for defining objects that have intrinsic properties."
- Joshua Bloch
Highlights
- Interfaces: Ideal for defining contracts and supporting multiple inheritance.
- Abstract Classes: Suitable for providing a common base for related classes, sharing code and behavior.
- Differences: Interfaces can have only abstract methods (prior to Java 8), while abstract classes can have both abstract and concrete methods.
- Usage: Interfaces are used for defining APIs and frameworks, while abstract classes are used for providing skeletal implementations.
Explore Further
Explore the power of interfaces and abstract classes in your own Java projects. Experiment with defining contracts using interfaces and providing shared functionality using abstract classes. Share your insights and experiences with the Java community to contribute to the collective knowledge and growth.
Any corrections or additions to this post are welcome.
Happy coding!π