Java abstract class
Created By: chatGPT
In Java, an abstract class is a class that cannot be instantiated on its own and typically contains one or more abstract methods that must be implemented by its subclasses. An abstract class is used to provide a base for subclasses to extend, allowing for a common interface while implementing specific behaviors in subclasses.
public abstract class Animal {
// Abstract method
public abstract void makeSound();
// Concrete method
public void eat() {
System.out.println("Eating...");
}
}
Subclasses that extend this abstract class must implement the abstract methods defined in it. Here's an example of how to implement a subclass that inherits from the
Animal
class.public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
You can have multiple subclasses that each provide their own implementation of the abstract methods. This allows you to utilize polymorphism. Here’s another example with a
Cat
subclass.public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
To use these classes, you would create instances of the subclasses and call their methods. Here's how you can do this.
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.makeSound(); // Outputs: Bark
dog.eat(); // Outputs: Eating...
Animal cat = new Cat();
cat.makeSound(); // Outputs: Meow
cat.eat(); // Outputs: Eating...
}
}