Creating a Subclass
Creating a subclass in Java involves extending an existing class to inherit its properties and behaviors, while also allowing the subclass to add its own unique features. Here’s a step-by-step guide to creating a subclass:
- Create the Superclass: First, define the superclass with the properties and behaviors you want to share with the subclass.
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
- Create the Subclass: To create a subclass, use the
extends
keyword followed by the name of the superclass.
public class Dog extends Animal {
public Dog(String name, int age) {
super(name, age); // Call superclass constructor
}
public void bark() {
System.out.println("Woof! Woof!");
}
}
- Accessing Superclass Members: The subclass inherits the properties and methods of the superclass. You can access them using the dot notation.
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3);
dog.eat(); // Inherited from Animal
dog.sleep(); // Inherited from Animal
dog.bark(); // Defined in Dog
}
}
In this example, Dog
is a subclass of Animal
. It inherits the name
and age
fields and the eat()
and sleep()
methods from Animal
. Additionally, Dog
introduces its own method bark()
.
When you create an instance of Dog
in the Main
class, you can access both the inherited methods from Animal
and the unique method bark()
defined in Dog
. This demonstrates how subclasses inherit properties and behaviors from their superclass while also being able to extend and modify them as needed.
let’s create a class that is a subclass of another class and override some methods. You’ll also get a basic feel for how packages work in this example.
Probably the most typical instance of creating a subclass, at least when you first start programming in Java, is creating an applet. All applets are subclasses of the class Applet (which is part of the java.applet
package). By creating a subclass of Applet, you automatically get all the behavior from the window toolkit and the layout classes that enable your applet to be drawn in the right place on the page and to interact with
system operations, such as keypresses and mouse clicks.
In this example, you’ll create an applet similar to the Hello World applet from yesterday, but one that draws the Hello string in a larger font and a different color. To start this example, let’s first construct the class
definition itself. Let’s go to your text editor, and enter the following class definition:
public class HelloAgainApplet extends java.applet.Applet {
}
Here, you’re creating a class called HelloAgainApplet. Note the part that says extends java.applet.Applet-that’s the part that says your applet class is a subclass of the Applet class. Note that because the
Applet class is contained in the java.applet package, you don’t have automatic access to that class, and you have to refer to it explicitly by package and class name.
The other part of this class definition is the public keyword. Public means that your class is available to the Java system at large once it is loaded. Most of the time you need to make a class public only if you want it to
be visible to all the other classes in your Java program, but applets, in particular, must be declared to be public. (You’ll learn more about public classes in Week 3.)
A class definition with nothing in it doesn’t really have much of a point; without adding or overriding any of its superclasses’ variables or methods, there’s no reason to create a subclass at all. Let’s add some information to
this class, inside the two enclosing braces, to make it different from its superclass.
First, add an instance variable to contain a Font object:
Font f = new Font(“TimesRoman”, Font.BOLD, 36);
The f instance variable now contains a new instance of the class Font, part of the java.awt package. This particular Font object is a Times Roman font, boldface, 36 points high. In the previous Hello World applet, the
font used for the text was the default font: 12-point Times Roman. Using a Font object, you can change the font of the text you draw in your applet.
By creating an instance variable to hold this font object, you make it available to all the methods in your class. Now let’s create a method that uses it.
When you write applets, there are several “standard” methods defined in the applet superclasses that you will commonly override in your applet class. These include methods to initialize the applet, to make it start running,
to handle operations such as mouse movements or mouse clicks, or to clean up when the applet stops running. One of those standard methods is the paint() method, which actually displays your applet onscreen. The
default definition of paint() doesn’t do anything-it’s an empty method. By overriding paint(), you tell the applet just what to draw on the screen. Here’s a definition of paint():
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello again!", 5, 40);
}
There are two things to know about the paint() method. First, note that this method is declared public, just as the applet itself was. The paint() method is actually public for a different reason-because the method
it’s overriding is also public. If a superclass’s method is defined as public, your override method also has to be public, or you’ll get an error when you compile the class.
Second, note that the paint() method takes a single argument: an instance of the Graphics class. The Graphics class provides platform-independent behavior for rendering fonts, colors, and behavior for drawing
basic lines and shapes. You’ll learn a lot more about the Graphics class in Week 2, when you create more extensive applets.
Inside your paint() method, you’ve done three things:
You’ve told the graphics object that the default drawing font will be the one contained in the instance variable f.
You’ve told the graphics object that the default color is an instance of the Color class for the color red.
Finally, you’ve drawn your “Hello Again!” string onto the screen, at the x and y positions of 5 and 25. The string will be rendered in the new font and color.
For an applet this simple, this is all you need to do. Here’s what the applet looks like so far:
public class HelloAgainApplet extends java.applet.Applet {
Font f = new Font("TimesRoman",Font.BOLD,36);
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello again!", 5, 40);
}
}
The final version of HelloAgainApplet.java.
1:import java.awt.Graphics;
2:import java.awt.Font;
3:import java.awt.Color;
4:
5:public class HelloAgainApplet extends java.applet.Applet {
6:
7: Font f = new Font("TimesRoman",Font.BOLD,36);
8:
9: public void paint(Graphics g) {
10: g.setFont(f);
11: g.setColor(Color.red);
12: g.drawString("Hello again!", 5, 40);
13: }
14:}