C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Abstract: We decorate the Page class with the abstract keyword. We also use an abstract method, one with no body.
ClassExtends: 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
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