Complex problems in programming are often split into simpler and shorter parts. A Java-program then mostly consists of multiple classes. There are two basic ways of how these classes are connected:
- Classes are connected hierarchically. This is called inheritance.
- Classes are build out of other classes. This is called composition.
Inheritance is important way of reusing specific program elements. It is based on the idea that parents pass certain attributes (variables) and abilities (methods), which can also be altered (overwritten), to their children. Syntactically inheritance is called with the key word extends. A extended class automatically has all non-private variables and methods of the upper class (superclass).
The following examples give a first impression of this programming technique.
// Tu20.java import ch.aplu.turtle.*; public class Tu20 extends Turtle { public Tu20() { speed(-1); setPos(-20, -80); for (int i = 0; i < 45; i++) { forward(200); right(159.6); } hideTurtle(); } public static void main(String[] args) { new Tu20(); } } |
The class RedTurtle inherits from the class Turtle. RedTurtle is a Turtle which now is red and draws red lines. In addition it has the new method star(). RedTurtle is a Turtle and so possesses all method of the class Turtle. The applicational class Tu20 generates an object t of the class RedTurtle and calls the method star().
|
Explaining the program code:
class Tu20 |
The class RedTurtle must be at the same location as the class Tu20 when compiling. Using the Online-Editor the easiest way to do this is to write the two class codes in the same editor window. |
// Tu22.java import ch.aplu.turtle.*; import java.awt.Color; public class MyTurtle extends Turtle { public Turtle setColor(Color c) { super.setColor(c); setPenColor(c); return this; } } public class Tu22 { public Tu22() { MyTurtle t = new MyTurtle(); t.setColor(Color.red); t.forward(100); } public static void main(String[] args) { new Tu22(); } } |
|
private | visible only in its own class |
public | visible everywhere |
protected | visible in the same package and in the subclasses |
If the modifier is missing, the default access right is protected.
If one wants to write in a good programming style it is important to deliberately use the modifiers and so limit the access rights as far as possible. Especially instance variables are strongly limited and mostly declared as private.