Explain the difference between abstract class and interface in Java, and in what scenarios would you use each one?
An abstract class in Java is a class that cannot be instantiated on its own and may contain both abstract and non-abstract methods. It can have instance variables and constructors. On the other hand, an interface in Java is a reference type similar to a class but can only contain constants, method signatures, default methods, static methods, and nested types. Interfaces cannot have instance variables.
You would use an abstract class in Java when you want to provide a common base set of functionalities that can be inherited by multiple subclasses. Abstract classes are useful when you want to define some methods that all subclasses must implement while providing other methods with default implementations. However, because Java does not support multiple inheritance, a subclass can only extend one abstract class.
An interface, on the other hand, is used in Java to define a contract for classes to implement. Interfaces are useful when you want to specify a set of methods that a class must implement, without providing any implementation details. Interfaces allow a class to implement multiple interfaces, making them more flexible than abstract classes in terms of code reusability.
In summary, use an abstract class in Java when you want to provide a common base implementation with some default behaviors, and use an interface when you want to define a contract for multiple classes to implement without specifying any implementation details.
Please login or Register to submit your answer