Q6: Explain the difference between an interface and an abstract class? When should you use one or the other?#
An abstract class can’t be instantiated, but it can be subclassed. An abstract class usually contains abstract and non-abstract methods that subclasses are forced to provide an implementation for.
An interface is a completely “abstract class” that is used to group related methods with empty bodies.
Each allow for advanced OOP constructions in Java.
Following are four main differences between abstract classes and interfaces:
-
An abstract class can have final variables, static variables, or class member variables whereas an interface can only have variables that are final and static by default.
-
An abstract class can have static, abstract, or non-abstract methods. An interface can have static, abstract, or default methods.
-
Members of an abstract class can have varying visibility of private, protected, or public. Whereas, in an interface all methods and constants are public.
-
A class can only extend another class, but it can implement multiple interfaces. Similarly, an interface can extend multiple interfaces. An interface never implements a class or an interface.
Use an abstract class when subclasses share state or use common functionality. Or you require to declare non-static, non-final fields or need access modifiers other than public.
Use an interface if you expect unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes. Interfaces are also used in instances where multiple inheritance of type is desired.
Q7: What is polymorphism? Can you give an example?#
Polymorphism is the ability in object-oriented programming to present the same interface for differing underlying forms or data types. Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code. What this means is that polymorphism allows your code to work with different classes without needing to know which class it’s using.
Polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.
The classic example of polymorphism is a Shape
class. We derive Circle
, Triangle
, and Rectangle
classes from the parent class Shape
, which exposes an abstract method draw(). The derived classes provide their custom implementations for the draw()
method. Now it is very easy to render the different types of shapes all contained within the same array by calling the draw()
method on each object. This saves us from creating separate draw methods for each shape e.g. drawTriangle()
, drawCircle()
etc.