Curriculum
In Java, an abstract class is a class that is declared using the “abstract” keyword, and it cannot be instantiated on its own. Instead, it is used as a base class for other classes to inherit from. An abstract class may contain one or more abstract methods, which are declared without an implementation. Subclasses of an abstract class must provide an implementation for all abstract methods inherited from the parent class, or they must also be declared as abstract classes.
Here’s an example to illustrate the concept of abstract classes and methods:
abstract class Animal { public abstract void makeSound(); public void eat() { System.out.println("The animal is eating."); } } class Cat extends Animal { public void makeSound() { System.out.println("Meow"); } } class Dog extends Animal { public void makeSound() { System.out.println("Woof"); } }
In the example above, the Animal
class is an abstract class that defines an abstract method makeSound()
and a non-abstract method eat()
. The Cat
and Dog
classes are subclasses of Animal
and they both provide an implementation for the makeSound()
method. However, they do not provide an implementation for the eat()
method, which is inherited from the Animal
class.
Here’s how you can use the Cat
and Dog
classes:
Animal animal1 = new Cat(); Animal animal2 = new Dog(); animal1.makeSound(); // Output: Meow animal2.makeSound(); // Output: Woof animal1.eat(); // Output: The animal is eating. animal2.eat(); // Output: The animal is eating.
In the example above, we create two instances of the Animal
class, one of type Cat
and one of type Dog
. We call the makeSound()
method on both instances, and they each output their respective sound. We also call the eat()
method on both instances, and they output the message defined in the Animal
class.
Note that it is not possible to create an instance of the Animal
class directly, because it is an abstract class. It can only be used as a base class for other classes to inherit from.