Abstract Classes
Classes that cannot be instantiated
5 min read
Abstract Classes
Abstract classes can have abstract and concrete methods. They cannot be instantiated.
Code Examples
Abstract class with concrete and abstract methods
java
1
2abstract class Animal {
3 abstract void sound();
4
5 void eat() {
6 System.out.println("Eating");
7 }
8}
9
10class Dog extends Animal {
11 void sound() {
12 System.out.println("Dog barks");
13 }
14}
15 Use Cases
- Base class with shared code
- Template method pattern
Common Mistakes to Avoid
- Trying to instantiate abstract class
- Forgetting to implement abstract methods