(November 13, 2014 Class hierarchies 1 ) Construction of classes with classes Classes can be built on existing classes through attributes of object types. Example: I A class PairOfDice can be constructed using two attributes of the type Dice. I A class CardDeck can be build with the help of an array of an object array containing 52 objects of the type Card I A class ListMap can be constructed with the help of ListNode objects I A class TrafficSystem can be constructed using objects from the classes Lane, Light, Vehicle... One use to say that this is a composition relation or a has relation.
(November 13, 2014 Class hierarchies 2 ) Class hierarchies A new class can also be built as a specialization of an existing class. Example: I The class StackException that is used in the Stack class is written as a sub class to Exception I If we have a class Vehicle, we can build new classes like Segway, Bicycle and Car. A Car can in turn be a base class for the classes Private car and Truck Vehicle Segway Bicycle Car Private Car Truck
In these cases you say that you have a class hierarchy I The class Vehicle is called a base class I The classes Segway, Bicycle and Car are derived classes or sub classes to the class Vehicle I A subclass (e. g. the class Car) can be used as a base class for other classes (e. g. Private car and Truck) One use to say the the phrase is a... that... can be used to identify when it is proper to use a class hierarchy. (November 13, 2014 Class hierarchies 3 )
(November 13, 2014 Class hierarchies 4 ) Inheritance An object of a sub class I has all the attributes and methods of the base class and I can add more by itself One say that the sub class inherits all the characteristics of the base class. Example: The class Car can have the attribute weight. A Private car can add npassenger while a Truck can add maxload. A subclass can also override methods and attributes in the baseclass.
(November 13, 2014 Class hierarchies 5 ) Unied Modeling Language (UML) The class hierarchies are often express in class diagrams in UML. Vehicle print() : void Segway Bicycle print() : void Car weight : double print() : void Private Car npassenger : int print() : void Truck maxload : double print() : void
public void print() { System.out.print("Car, weight " + weight); (November 13, 2014 Class hierarchies 6 ) The Vehicle hierarchy in code public class Vehicle { public void print() { System.out.print("Vehicle"); public class Segway extends Vehicle { public class Bicycle extends Vehicle { public void print() { System.out.print("Bicycle"); public class Car extends Vehicle { double weight; public Car( double v ) { weight = v;
Usage The code... public static void pr(string s) { System.out.print(s); public static void main(string [] args) { Vehicle f = new Vehicle(); Segway s = new Segway(); Bicycle c = new Bicycle(); Car b = new Car(1.2); pr("f: "); f.print(); pr("\n"); pr("s: "); s.print(); pr("\n"); pr("c: "); c.print(); pr("\n"); pr("b: "); b.print(); pr("\n");... give the printout f: Vehicle s: Vehicle c: Bicycle b: Car, weight 1.2 (November 13, 2014 Class hierarchies 7 )
(November 13, 2014 Class hierarchies 8 ) More subclasses public class PrivateCar extends Car { int npassenger = 5; public PrivateCar(double v) { super(v); public PrivateCar(double v, int ant) { super(v); npassenger = ant; public void print() { System.out.print("Private"); super.print(); System.out.print(", number of passengers " + npassenger);
(November 13, 2014 Class hierarchies 9 ) Continuation of main... PrivateCar pb1 = new PrivateCar(1.5); PrivateCar pb2 = new PrivateCar(0.9,4); pr("pb1: "); pb1.print(); pr("\n"); pr("weight b : " + b.weight + "\n"); pr("weight pb1: " + pb1.weight + "\n"); f = b; pr("f: "); f.print(); pr("\n"); f = pb1; pr("f: "); f.print(); pr("\n"); pb1 = (PrivateCar) f; pr("pb1: "); pb1.print(); pr("\n"); gives the printout pb1: PrivateCar, weight 1.5 and number of passengers 5 Weight b: 1.2 Weight pb1: 1.5 f: Car, weight 1.2 f: PrivateCar, weight 0.9 and number of passengers 4 pb1: PrivateCar, weight 0.9 and number of passengers 4
(November 13, 2014 Class hierarchies 10 ) Example of illegal operations pb1 = f; pb1 = (PrivateCar) c; pr("weight: " + f.weight); pb1 = (PrivateCar) f; // if f don't refer a PrivateCar The last can be made safe through if ( f instanceof PrivateCar ) pb1 = (PrivateCar) f; else... The operator instanceof should be used with caution
Conclusions If the class S is a subclass of the class B and if s is declared as a reference to S and b to B we have I An object of the class S has all attributes and methods that the class B have I If S declares an attribute that are declared B, that attribute is overridden by B's attribute. I A reference can refer objects of the declared class and its subclasses. I The construction b.x (or b.x()) requires that the attribute (or method) x is declared in B or any of B's baseclasses. I When you use an attribute a through dot notation p.a, it is the declaration of p that settles what attributes are used. I When you call a method m using p.m(), it is the type of the element that p refers that settles what method is selected. (so called dynamic or late binding). (November 13, 2014 Class hierarchies 11 )
(November 13, 2014 Class hierarchies 12 ) Methods that only are declared in selected classes Vehicle print() : void Segway Bicycle print() : void Car weight : double print() : void Private Car npassenger : int print() : void tax() : double Truck maxload : double print() : void tax() : double Cars are taxed, but the calculations are done in dierent way for private cars and trucks.
(November 13, 2014 Class hierarchies 13 ) Usage of the tax-method Car b = new Truck(3., 2.);... if (...) { b = new PrivateCar(1.2, 5);... double s; s = b.tax(); s = ((Truck) b).tax(); // Illegal! No tax in b // Risky! if ( b instanceof Truck ) // Works but clumsy s = ((Truck) b).tax(); // and inflexible else if ( b instanceof PrivateCar ) s = ((PrivateCar) b).tax(); else s = 0;
Better Dene also a method tax-method in the class Car or, better, in the class Vehicle: Vehicle print() : void tax() : double Segway Bicycle print() : void Car weight : double print() : void Private Car npassenger : int print() : void tax() : double Truck maxload : double print() : void tax() : double public class Vehicle { public void print() { System.out.print("Vehicle"); public double tax() { return 0; (November 13, 2014 Class hierarchies 14 )
(November 13, 2014 Class hierarchies 15 ) Levels of protection I private Only accessible from the classes own methods I public Accessible for all I protected Accessible from subclasses and classes in the same package I package If no level of protection is given. all classes are assigned package access level
(November 13, 2014 Class hierarchies 16 ) Constructors in inheritance Constructors are not inherited When an object of a subclass is created, the following steps are taken: 1. Instance variables take their default values 2. A constructor for the base class (super class) is called. You use the keyword super to specify which constructor in the base class that should be used. If super is not used, the parameterless constructor in the base class are used, in this case there has to exist such a constructor. 3. If there are initializarions they are evaluated and assigned to the respective attributes. 4. The statements in the constructor in the subclass are executed. Use super to avoid repeating code!
(November 13, 2014 Class hierarchies 17 ) Standard software in Java The Java environment is based on inheritance and class hierarchies! Example: 1. The classes for exceptions: Throwable with the subclasses Error and Exception with the subclasses... 2. Graphical components: Component with subclasses Button, Checkbox, Container,... where e. g. Container has the subclasses Panel, Window... 3. Maps: Map with (among others) the subclasss HashMap 4. The Collection classes: Collection with (among others) the subclass List that have the subclasses Vector and LinkedList (Map, Collection are List actually interfaces interface and not classes)
The Class Object The class Object is the baseclass to all classes. A reference to Object can thus refer any object. This can be used to construct general collection classes (lists, tables or... ): class ListNode { Object info; ListNode next; ListHead(Object i, ListNode n) { info = l; next = n; public class List { ListNode head; public void insertfirst(object o) { head = new ListNode(o, head)... (November 13, 2014 Class hierarchies 18 )
The class Object cont Some methods in the class Object: I Object clone() I boolean equals(object o) I String tostring() You often have reasons to override these! (November 13, 2014 Class hierarchies 19 )
(November 13, 2014 Class hierarchies 20 ) An example of using inheritance: geometrical gures Write a program that can handle pictures of circles, rectangles and other geometrical shapes. The program should be able to I represent a number of dierent shapes. I Draw an image of the represented shapes. I Compute the accumulated area of all gures. I Read rules about the structure of a certain shape. (other operations are of course possible: move, rotate, scale... )
(November 13, 2014 Class hierarchies 21 ) Cont geometrical gures 1. Which classes are needed to represent the gures? Circle, Rectangle,... 2. What attributes and methods should we have? I constructors I methods for calculating areas I methods for drawing 3. How should one represent a collection of such gures? I array? I list? I other structure? What type should be used for the elements in the structure?
(November 13, 2014 Class hierarchies 22 ) Cont geometrical gures Shape xcoord : int ycoord : int area() : double paint():void Circle radius: int area(): double paint():void Rectangle width : int height : int area() : double paint():void
(November 13, 2014 Class hierarchies 23 ) Cont geometrical gures Now we can e. g. do Shape[] fig = new Shape[100]; fig[0] = new Rectangle(...); fig[1] = new Circle(...);... (but we are to use a more exible structure than an array) There is no meningful implementation of area() and paint() in Shape! Declare these methods and the class Shape as abstract.
(November 13, 2014 Class hierarchies 24 ) Cont geometrical gures import java.awt.*; public abstract class Shape { protected int xcoord, ycoord; public Shape(int x, int y) { xcoord = x; ycoord = y; public abstract double area(); public abstract void paint(graphics g);
(November 13, 2014 Class hierarchies 25 ) Cont geometrical gures import java.awt.*; public class Circle extends Shape { protected int radius; public Circle(int x, int y, int r){ super(x,y); radius = r; public double area(){ return Math.PI*radius*radius; public void paint(graphics g){ g.setcolor(color.red); g.filloval(xcoord-radius, ycoord-radius, 2*radius, 2*radius);
(November 13, 2014 Class hierarchies 26 ) Cont geometrical gures import java.awt.*; public class Rectangle extends Shape { protected int width, height; public Rectangle(int x, int y, int w, int h) { super(x,y); width = w; height = h; public double area(){ return width*height; public void paint(graphics g){ g.setcolor(color.blue); g.fillrect(xcoord,ycoord,width,height);
(November 13, 2014 Class hierarchies 27 ) Cont geometrical gures To collect a number of dierent gures we use one of the collection classes in Java: LinkedList that is a (indirect) subclass to Collection (actually an interface). For this task, it is sucient to I Crete a LinkedList object: Collection<Shape> shapes = new LinkedList<Shape>(); I Add gures to the list, e. g.: shapes.add(new Circle(x,y,r)); I Iterate over the elements and access their methods. E. g: for (Shape s:shapes) s.paint();
Cont geometrical gures import javax.swing.*; import java.awt.*; import java.util.*; public class Drawing extends JPanel { private Collection<Shape> shapes; public Drawing(Collection<Shape> s, int w, int h) { shapes = s; setbackground(color.white); setpreferredsize(new Dimension(w,h)); public double area(){ double a = 0; for (Shape s:shapes) a += s.area(); return a; public void paintcomponent(graphics g){ super.paintcomponent(g); for (Shape s:shapes) s.paint(g); (November 13, 2014 Class hierarchies 28 )
(November 13, 2014 Class hierarchies 29 ) Cont geometrical gures import javax.swing.*; import java.awt.*; import java.util.*; public class DrawTest extends JFrame { public static void main(string[] args){ Collection<Shape> shapes = read(new Scanner(System.in)); Drawing d=new Drawing(shapes,400,400); System.out.println("Total area: " + (int)d.area()); new DrawTest(d); public DrawTest(Drawing d){ getcontentpane().add(d); pack(); settitle("drawtest"); setdefaultcloseoperation(exit_on_close); setvisible(true);
Cont geometrical gures private static Collection<Shape> read(scanner sc){ Collection<Shape> shapes = new LinkedList<Shape>(); while (sc.hasnext()){ String s=sc.next(); if (s.equals("circle")){ int x, y, r; x = sc.nextint(); y = sc.nextint(); r = sc.nextint(); shapes.add(new Circle(x,y,r)); else { int x, y, w, h; x = sc.nextint(); y = sc.nextint(); w = sc.nextint(); h = sc.nextint(); shapes.add(new Rectangle(x,y,w,h)); return shapes; (November 13, 2014 Class hierarchies 30 )
(November 13, 2014 Class hierarchies 31 ) Cont geometrical gures Note how the classes are based on inheritance. They inherit from the graphical classes in Java. Details in graphics are outside the scope of this course. If you run the program with java DrawTest < figure.txt and the le figure.txt contain rectangle 20 50 200 30 circle 350 100 30 rectangle 300 200 50 150 circle 100 300 80
Cont geometrical gures (November 13, 2014 Class hierarchies 32 )