Introduce Java abstract Keyword and give examples
In Java, the abstract
keyword is used to declare a class or a method that is incomplete and must be implemented by subclasses. It is a fundamental concept in object-oriented programming that supports abstraction and helps in defining a common interface for different classes.
An abstract class cannot be instantiated on its own and may contain abstract methods (methods without a body) as well as concrete methods (methods with a body). Subclasses that extend an abstract class must provide implementations for all abstract methods.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void sound();
// Concrete method
void sleep() {
System.out.println("Sleeping...");
}
}
// Subclass that extends the abstract class
class Dog extends Animal {
// Implementing the abstract method
void sound() {
System.out.println("Bark");
}
}
// Subclass that extends the abstract class
class Cat extends Animal {
// Implementing the abstract method
void sound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.sound(); // Output: Bark
myDog.sleep(); // Output: Sleeping...
myCat.sound(); // Output: Meow
myCat.sleep(); // Output: Sleeping...
}
}
An abstract method is a method that is declared without an implementation. It must be implemented by any non-abstract subclass.
abstract class Shape {
// Abstract method
abstract void draw();
}
class Circle extends Shape {
// Implementing the abstract method
void draw() {
System.out.println("Drawing a Circle");
}
}
class Rectangle extends Shape {
// Implementing the abstract method
void draw() {
System.out.println("Drawing a Rectangle");
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();
circle.draw(); // Output: Drawing a Circle
rectangle.draw(); // Output: Drawing a Rectangle
}
}
Using the abstract
keyword effectively allows you to define a common interface for a group of related classes while leaving the implementation details to the subclasses. This promotes code reusability and a cleaner design.