In Java, abstract classes and methods provide a way to define methods that must be implemented by subclasses, while also allowing the abstract class to provide some default behavior. Here are some key points and examples to illustrate how to create and extend abstract classes in Java:
final
or private
.Let's start by defining an abstract class with both abstract and non-abstract methods.
abstract class Animal {
// Abstract method (does not have a body)
abstract void makeSound();
// Non-abstract method (has a body)
void sleep() {
System.out.println("Sleeping...");
}
}
Next, we'll create a concrete subclass that extends the abstract class and implements the abstract method.
class Dog extends Animal {
// Implement the abstract method
@Override
void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
// Implement the abstract method
@Override
void makeSound() {
System.out.println("Meow");
}
}
Finally, we can create instances of the concrete subclasses and use them.
public class Test {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // Outputs "Bark"
myDog.sleep(); // Outputs "Sleeping..."
myCat.makeSound(); // Outputs "Meow"
myCat.sleep(); // Outputs "Sleeping..."
}
}
Animal
class is abstract and defines an abstract method makeSound()
and a concrete method sleep()
.Dog
and Cat
classes extend the Animal
class and provide implementations for the makeSound()
method. They inherit the sleep()
method as it is.Test
class, instances of Dog
and Cat
are created. The makeSound()
method is called on each instance, demonstrating polymorphism. The sleep()
method is also called, showing inheritance of non-abstract methods.final
or private
because they are meant to be extended and implemented by subclasses.By following these rules and utilizing abstract classes and methods, you can define clear and flexible APIs in Java, ensuring that certain behaviors are enforced while allowing for specific implementations in subclasses.