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
detailsMost classes can be instantiated with "new." An abstract
class
cannot be. Instead we must create an instance of a derived class
.
class
with the abstract
keyword. We also use an abstract
method, one with no body.class
. They are not abstract
. Neither are their open methods.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
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
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 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.