|
|
Inheritance Syntax
|
One of the most useful techniques in object-oriented programming is the use of inheritance.
Inheritance allows the programmer to evolve through steps in programming. First, you declare a general
age-old "Shape" class. This Shape only has an attribute of "type" and two methods for drawing the Shape
and telling the "type" of Shape.
class Shape {
class-scope {
}
object-scope {
private String type ;
public String whatType () {
return type ;
}
public void draw () {
}
public makeInstance (String type) {
this.type = type ;
}
public makeInstance () {
this.type = "generic" ;
}
}
}
And now we define a "generic" Shape:
Shape jShape = Shape.makeInstance () ;
String type = jShape.whatType () ;
// type = "generic"
Now you need to extend the Shape because nothing much can be done with it. You do this through
inheritance:
class Rectangular inherits Shape {
class-scope {
}
object-scope {
private float width ;
private float length ;
public makeInstance (float
width, float length, String type) {
super (type) ;
this.width = width ;
this.length = length ;
}
}
}
And then:
Rectangular rect ;
rect = Rectangular.makeInstance (10,20,"rect") ;
String type = rect.whatType () ;
// type = "rect"
// We have a Shape that is not generic. It is // the type of "rect".
// "whatType" is not seen in the Rectangular, // because it has been inherited from Shape.
// However, it can be used.
|
Contents | Previous
|
|
|