An abstract class is like a blueprint for other classes. You can’t create an object directly from an abstract class. Instead, you use it as a foundation for other classes that can build upon it and fill in the details.
Abstract classes are useful when you want to define a general concept that has some shared features, but you also want to leave room for specific details that can vary in different situations. For example, you might have a general concept of an "Animal" that includes common features like eating or sleeping, but different animals might eat or sleep in different ways.
Here’s how you might create an abstract class called Animal:
public abstract class Animal { abstract void makeSound(); // Abstract method, no body void sleep() { System.out.println("This animal sleeps."); } }
In this example, makeSound() is an abstract method, meaning it doesn’t have a body yet. The sleep() method, however, is fully implemented.
Now, let’s create some classes that extend the Animal class:
public class Dog extends Animal { void makeSound() { System.out.println("The dog barks."); } } public class Cat extends Animal { void makeSound() { System.out.println("The cat meows."); } }
Both Dog and Cat classes must provide their own version of the makeSound() method, but they inherit the sleep() method as is.
An abstract class is great when you have some methods that should be shared among all child classes, but you also want to force some methods to be defined by those child classes.
public abstract class Bird extends Animal { void move() { System.out.println("The bird flies."); } }
Now, any class that extends Bird will inherit both the move() method and the sleep() method from Animal, but still needs to implement makeSound().
Abstract classes in Java provide a way to create a shared foundation for related classes while leaving room for those classes to define specific details. They strike a balance between shared functionality and flexibility, making your code both powerful and reusable.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3