Published by: Dikshya
Published date: 30 Jun 2023
Interfaces and abstract classes are both mechanisms used in object-oriented programming to define common behavior and provide a level of abstraction. However, there are some key differences between them:
Definition:
Multiple Inheritance:
Method Implementation:
Constructors:
Accessibility:
Usage:
Here's an example of an abstract class in Java:
// Abstract class
abstract class Animal {
// Abstract method (no implementation)
public abstract void makeSound();
// Concrete method (with implementation)
public void sleep() {
System.out.println("Zzzz...");
}
}
// Subclass of the abstract class
class Dog extends Animal {
public void makeSound() {
System.out.println("Woof!");
}
}
// Subclass of the abstract class
class Cat extends Animal {
public void makeSound() {
System.out.println("Meow!");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound(); // Output: Woof!
dog.sleep(); // Output: Zzzz...
Cat cat = new Cat();
cat.makeSound(); // Output: Meow!
cat.sleep(); // Output: Zzzz...
}
}
In the example above, Animal
is an abstract class that contains an abstract method makeSound()
and a concrete method sleep()
. The makeSound()
method is declared as abstract in the Animal
class, meaning it does not have an implementation in the abstract class itself. The Dog
and Cat
classes are concrete subclasses of the Animal
class, and they provide their own implementation for the makeSound()
method. They also inherit the sleep()
method from the Animal
class.
In the Main
class, we create objects of Dog
and Cat
classes and call their respective methods. The makeSound()
method outputs the sound specific to each animal, while the sleep()
method is inherited from the Animal
class.