Course Content
Introduction to Java
Abstract classes are special classes in Java that can't be instantiated on their own. Instead, you need to create a subclass that extends the abstract class and provides an implementation for the abstract methods.
Think of an abstract class as a blueprint for other classes. It can contain both abstract methods and concrete methods (methods with a body). Concrete methods in an abstract class can be used by subclasses as is, but subclasses must override abstract methods.
Let's take a look at an example to understand this better. Suppose we have an abstract class Element
:
Main.java
Now, we can create two subclasses Square
and Triangle
, that extend Element
:
Main.java
You can use the Element
class as a blueprint for creating objects of subclasses. The following code will call the drawing method for each object and produce different outputs:
Main.java
Can you see how abstract classes are making our code more organized and maintainable? By using abstract classes, we can define a common set of methods that all subclasses must implement. There are a few things to know about abstract classes:
- Abstract classes can have non-abstract methods (methods with a body), which subclasses can use;
- In Java, you can't create an object of an abstract class using the new keyword;
- If a class contains at least one abstract method, then the class must be declared as abstract. On the other hand, if a class doesn't contain any abstract methods, then there's no need to declare it as abstract;
- You can extend only one abstract class in Java. However, you can implement multiple interfaces;
- You can also define an abstract class without any abstract methods.
That's it for abstract classes! Let's get to the questions.
What is an abstract class in Java?
Select the correct answer
Can an abstract class contain an abstract method?
Select the correct answer
Section 3.
Chapter 3