HomeSearch

Java Abstract Class

Use the abstract keyword, creating classes that derive from an abstract class.
Abstract. This keyword is used on classes. It does not indicate a style of art. It indicates a "template-only" class, one that cannot be created directly.
Class details. Most classes can be instantiated with "new." An abstract class cannot be. Instead we must create an instance of a derived class.

Abstract: We decorate the Page class with the abstract keyword. We also use an abstract method, one with no body.

Class

Extends: Article and Post are derived from the Page class. They are not abstract. Neither are their open methods.

Here: We create instances of Article and Post, but use them with a Page reference. We call open(). The derived open methods are used.

Java program that uses abstract class abstract class Page { public abstract void open(); } class Article extends Page { public void open() { System.out.println("Article.open"); } } class Post extends Page { public void open() { System.out.println("Post.open"); } } public class Program { public static void main(String[] args) { // We cannot directly create a Page. Page page = new Article(); page.open(); Page page2 = new Post(); page2.open(); } } Output Article.open Post.open
Cannot instantiate. We cannot create a new abstract class with new. This will result in a "cannot instantiate the type" error. The program cannot be run.
Java program that causes abstract error abstract class Ghost { } public class Program { public static void main(String[] args) { Ghost ghost = new Ghost(); } } Output Cannot instantiate the type Ghost
Some notes. The term "abstraction" implies something indirect and more general than a concrete object. The word "animal" is an abstraction for a dog, cat or fish.
In Java, we use an abstract class to create a type that can only be used when added to other classes. This is a powerful feature of object-oriented programming.
A summary. A website can have many types of Pages. The Page class is an abstract class for the more derived documents. With abstract classes we unlock a powerful feature of Java.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls