Abstract Classes and Interfaces

Implementing Abstract Classes

🙋 Need help? Ask an expert now!

In Java an "abstract" class is a class that cannot be instanced but is a superclass for several other related subclasses. The abstract class contains abstract and non-abstract methods, variables, and even constructors that the subclass inherits. The Java reserved word abstract can only be used in an abstract class and will cause an error if used in a regular class. This is how an abstract class can be utilized.

AbstractClassTest.java
package exlcode;

public abstract class AbstractClassTest {

  // abstract methods only have to be declared
  abstract void print();

  abstract void printGreeting();
}
AbstractClassesExample.java
package exlcode;

public class AbstractClassesExample extends AbstractClassTest {

  public static void main(String[] args) {
    AbstractClassesExample abstractClassesExample = new AbstractClassesExample();
    abstractClassesExample.print();
    abstractClassesExample.printGreeting();
  }

  // implements the abstract method print()
  public void print() {
    System.out.println("Java World");
  }

  // implements the abstract method printGreeting()
  public void printGreeting() {
    System.out.println("Hello World!");
  }
}

The class AbstractClassesExample inherits the two abstract methods print() and printGreeting() from the abstract class AbstractClassTest. When extending from an abstract class, we first define a method with the same name as an abstract method before overriding them with the proper method in a regular class. If print() or printGreeting() did not exist in the AbstractClassesExample class, it would cause an error. In a rare situation where necessary, an abstract class can also extend and implement another abstract class.

Application Question

Which of the following statements about a class that contains an abstract method is(are) true?

I. You can't have any constructors in this class.
II. This class must be declared as abstract.
III. You can't declare any fields in this class.