When to use abstract classes and interface in Java?
What is an abstract class?
In java, an abstract class which cannot be instantiated, which means it cannot make objects out of it. It act as a foundation or model for classes that augment in it.
A class that is abstract may have both abstract and non-abstract methods. Abstract methods lack a body because they are stated without an implementation. Any subclass that extends the abstract class must implement these methods. On the other hand, non-abstract methods contain a body and can be called straight from the subclass without requiring any additional implementation.
If we want to create an abstract class in java, then we will use the abstract keyword in the class definition.
For example:
public abstract class Animal{ // abstract method public abstract void makeSound(); // non-abstract method public void sleep() { System.out.println("zzz"); } }
The Animal class in the example above contains one abstract method, makeSound(), and one non-abstract method, sleep(), and is declared to be abstract. The makeSound() method must be implemented by any subclass that extends the Animal class, however the sleep() method can be used directly without any additional implementation.
When to use abstract classes in java?
When designing a base class or common interface for a collection of related classes in Java, but avoiding explicitly instantiating objects of that base class, abstract classes should be utilised.
The following are some scenarios where abstract classes are frequently employed:
- For a collection of related classes, a common interface should be created: We can use an abstract class to declare the common methods and properties and leave the implementation specifics to the individual subclasses when we have a group of classes that share common methods and properties but each class needs to implement those methods independently.
- To provide a partial implementation: We can use an abstract class to provide a partial implementation of the common behaviour while leaving the additional behaviour up to the individual subclasses when we have a group of related classes that share some common behaviour but also need to implement some additional behaviour.
- To enforce a contract: We can specify certain methods as abstract methods in an abstract class when we want to guarantee that they are implemented in each and every subclass of a specific class. This ensures that the contract is upheld by requiring the subclasses to implement those methods.
- To provide a level of abstraction: An abstract class can be used to specify the interface and offer a default implementation for some of the methods in a class hierarchy to give a level of abstraction while hiding the implementation specifics from the user. Means the user now can work with the abstract classes without any concern about the implementation on the finer points.
- To support polymorphism: In order to allow polymorphism, we can create objects of various subclasses that can be considered as objects of the same abstract class by using abstract classes. Means we now may employ polymorphism and we can create code that is more adaptive and dependable.
Generally speaking, abstract classes are an effective Java tool for writing flexible and maintainable code.
What is interface in java?
In java, an interface is a group of abstract methods that is use to form a contract or a set of method so that every class that implements the interface must implement. It offers a means of defining a collection of associated methods that may be accessed by several unconnected classes.
The Java "interface" keyword is used to declare an interface. Interface does not coati any method implementation it is use to only contain method signature and constants. Instead, it is up to the classes that implement the interface to implement the methods.
Lets take an example:
public interface Shape { public double getArea(); public double getPerimeter(); }
As you can all see in the above example we have getArea and getPerimeter that is used to refer to two methods on the shape interface. Both of these methods must be implemented by any class that conforms to this interface.
A class must use the "implements" keyword and give an implementation for each of the interface's methods in order to implement an interface.
For example:
public class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } public double getArea() { return Math.PI * radius * radius; } public double getPerimeter() { return 2 * Math.PI * radius; } }
When to use interface in java?
Java interfaces are used to specify a collection of linked methods that can be implemented by numerous unrelated classes. They offer a means of defining a typical behaviour or contract that may be applied uniformly across several classes. The following are some situations in which Java interfaces are used:
- When you want to specify a contract: Interfaces are used to specify a contract or a group of methods that all classes that implement the interface must adhere to. By doing this, you can be certain that the implementation is the same for all classes that implement the interface.
- When many inheritances are desired: Java does not permit multiple class inheritance, although it does permit the implementation of numerous interfaces. This implies that a class can implement several interfaces and inherit all of their declared methods and attributes.
- When you want to decouple implementation: When it is desired to separate the implementation from the interface, interfaces offer a means of doing so. This makes the code more adaptable and simpler to maintain because changes to the implementation won't affect the interface.
- When you want to achieve loose coupling: Interfaces are frequently used to provide loose connectivity between components when you want to. Components can be swapped out with ease without affecting the rest of the system by programming to interfaces rather than specific implementations.
- When you want to define a set of constants: When defining a set of constants, interfaces can also be utilised. Interfaces can be used to specify a set of constants that are shared by several classes. This makes the code more manageable and helps to prevent code duplication.
In conclusion, Java interfaces are used to establish multiple inheritance, divorce implementation from interface, achieve loose coupling, define a collection of constants, and create a group of related methods that can be implemented by several unrelated classes. They offer a potent tool for writing adaptable and dependable code.
Limitation of interface
Java interfaces contain various restrictions that programmers should be aware of. The following are some interfaces' drawbacks:
- No implementation: Java interfaces can only provide method signatures; they cannot specify how they should be implemented. This implies that any class that implements the interface must offer a unique implementation of each of the interface's methods.
- Cannot contain fields: Except for public static final constants, interfaces are unable to contain fields. This can restrict the functionality of interfaces by preventing them from having instance variables.
- Cannot be instantiated: Interfaces cannot be directly instantiated, which prevents them from being utilised as stand-alone objects. Instead, a class must implement them, which can complicate the coding.
- Cannot change after compilation: After an interface has been compiled, it cannot be updated to modify its methods or signatures. As a result, it may be challenging to alter an interface over time and may cause compatibility problems.
- Can lead to code duplication: Code duplication may result from the necessity for many classes to independently implement methods with similar signatures across various interfaces.
The inability to contain implementation or fields, the inability to be instantiated, the impossibility to alter after compilation, and the potential for code duplication are a few restrictions placed on interfaces in Java. When planning the architecture of their product, developers should be aware of these constraints.