Abstract. This Java 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.
With this keyword, we can create templates that other classes can build upon. But an abstract class is not one that we want to create and use in other ways.
Class details. Most classes can be instantiated with "new." An abstract class cannot be. Instead we must create an instance of a derived class.
Info We decorate the Page class with the abstract keyword. We also use an abstract method, one with no body.
Tip 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.
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();
}
}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.
abstract class Ghost {
}
public class Program {
public static void main(String[] args) {
Ghost ghost = new Ghost();
}
}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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 10, 2024 (edit).