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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 10, 2024 (edit).