GUI Demo: A Huge Use for Inheritance
To make a GUI in JavaFX, you inherit from the class
Application
; this makes your object an instance
of the abstract class Application
import javafx.application.Application;
public class Window extends Application
{
}
When we tried to compile, this happened.
unix> javafxc Window.java
Window.java:3: error: Window is not abstract and does not override abstract method start(Stage) in Application
public class Window extends Application
^
1 error
unix>
Why? The method start
is marked abstract
,
so any child class of Application
must implement it. This
works in the same manner as a specified method in an interface.
Let's to a minimal implementation. Note that another import is needed.
import javafx.application.Application;
import javafx.stage.Stage;
public class Window extends Application
{
@Override
public void start(Stage primary)
{
primary.setTitle("My first GUI App")
}
}
Let's get the window to appear.
Rules for the abstract
Keyword
A class is concrete if it is not an abstract class.
- Instances of abstract classes cannot be created. This is enforced by the compiler.
- Any class can be marked abstract; do this if it makes no sense to create instances of the class.
- If a method has no implementation in a class, it must be marked abstract.
- A class containing an abstract method must be marked abstract.
- Any concrete child class of an abstract class must implement all of the parent class's methods, either directly or via inheritance. This is enforced by the compiler.
What can an abstract class do that an interface can't Abstract classes can have state and constructors. Abstract classes can contain both abstract and implemented methods. They represent a hybrid between interfaces and concrete classes.
What is protected
? This means a
method or a piece of state is visible to child classes as well as inside
of the class. I use this very sparingly. Private methods in parent
classes can be initalized via super
.