1 Answers
Abstract Class vs Interface in Java
In Java, an abstract class and an interface are both used to define the structure of classes and provide common behavior, but they have key differences:
Abstract Class:
- Can contain both abstract and non-abstract methods.
- Can have fields, constructors, and method implementations.
- Can extend only one class but implement multiple interfaces.
Interface:
- Contains only abstract methods by default.
- Cannot have method implementations or fields.
- Supports multiple inheritance - a class can implement multiple interfaces.
Example Usage:
Abstract Class Example:
abstract class Animal { String name; public abstract void makeSound(); public void printName() { System.out.println("Name: " + name); } }
Interface Example:
interface Vehicle { void start(); void stop(); } class Car implements Vehicle { @Override public void start() { System.out.println("Car started"); } @Override public void stop() { System.out.println("Car stopped"); } }
In summary, use an abstract class when you want to provide a common functionality along with abstract methods, and use an interface when you want to define a contract for classes to implement certain methods.
Please login or Register to submit your answer