Block IQ Marko Boon (marko@win.tue.nl) Jacques Resing (resing@win.tue.nl)
Part II: Object Oriented Programming 2/266 1. Objects and Classes 2. Class Inheritance and Interfaces 3. Some Predefined Java Classes 4. Object Oriented Software Development
Object Oriented Programming Programming techniques (learning curve of someone who learns to program): 3/266 1. unstructured programming, 2. procedural programming, 3. modular programming, 4. object-oriented programming.
Unstructured Programming Test.java class Test { 4/266 public static void main(string[] arg) { double complexre = 3; double complexim = 2; double a = Math.sqrt(complexRe*complexRe + complexim*complexim);
Procedural Programming Test.java class Test { 5/266 static double complexabs(double real, double imag) { return Math.sqrt(real*real + imag*imag); public static void main(string[] arg) { double complexre = 3; double complexim = 2; double a = complexabs(complexre, complexim);
Modular Programming Complex.java class Complex { 6/266 static double abs(double real, double imag) { return Math.sqrt(real*real + imag*imag); Test.java public static void main(string[] arg) { double complexre = 3; double complexim = 2; double a = Complex.abs(complexRe, complexim);
1. Objects and classes Programming in procedural languages like C, Pascal, BASIC involves choosing data structures, designing algorithms, and translating algorithms into code. In procedural programming, data and operations on the data are separate, and this methodology requires sending data to procedures and functions. Object oriented programming places data and the operations that pertain to them within a single entity called an object. This approach organises programs in a way that mirrors the real world, in which all objects are associated with both attributes and activities. Programming in Java involves thinking in terms of objects. A Java program can be viewed as a collection of cooperating objects. 7/266
Objects An object represents an entity in the real world that can be distinctly defined. For example, a student, a house, a vehicle, a circle etc.. An object has a unique identity, a state and behaviours. The state is defined by a set of properties (they can be regarded as variables within the object). The behaviour is defined by a set of methods. 8/266
Classes A Class is a construct that defines objects of the same type. In a Java class, data are used to describe properties, and methods are used to define behaviours. 9/266 + F A N E @ K > A H A @ K > A = > I @ K > A = @ @ + F A N L E @ = H C @ K > A + F A N @ K > A @ K > A C A J + K C = J A + F A N I K > J H =? J + F A N L E @ The methods abs and arg return information about the object. The methods add and subtract modify (the state of) the object. The method getconjugate constructs a new Complex object. Complex is a constructor.
Constructors Each class must have at least one constructor which is used to create objects of this class. 10/266 This is wrong: Complex c; c.re = 3; c.im = 5; It will result in a compiler error:
Writing a class in Java 11/266 public class Complex {
Writing a class in Java 12/266 public class Complex { // properties // constructor(s) // methods
Writing a class in Java 13/266 public class Complex { private double re; private double im; // constructor(s) // methods
Writing a class in Java 14/266 public class Complex { private double re; private double im; public Complex(double real, double imaginary) { // methods
Writing a class in Java 15/266 public class Complex { private double re; private double im; public Complex(double real, double imaginary) { this.re = real; this.im = imaginary; // methods
Writing a class in Java 16/266 public class Complex { private double re; private double im; public Complex(double real, double imaginary) { this.re = real; this.im = imaginary; public double abs() { return Math.sqrt(re*re + im*im); You can use this.re and this.im if you want.
Writing a class in Java Some other methods: public void add(complex c) { 17/266 public Complex getconjugate() { public void multiply(complex c) {
Writing a class in Java Some other methods: public void add(complex c) { re += c.re; 18/266 public Complex getconjugate() { public void multiply(complex c) {
Writing a class in Java Some other methods: public void add(complex c) { re += c.re; im += c.im; 19/266 public Complex getconjugate() { public void multiply(complex c) {
Writing a class in Java Some other methods: public void add(complex c) { re += c.re; im += c.im; 20/266 public Complex getconjugate() { return new Complex(re, -im); public void multiply(complex c) {
Writing a class in Java Some other methods: public void add(complex c) { re += c.re; im += c.im; 21/266 public Complex getconjugate() { return new Complex(re, -im); public void multiply(complex c) { double newre = re * c.re - im * c.im; double newim = re * c.im + im * c.re;
Writing a class in Java Some other methods: public void add(complex c) { re += c.re; im += c.im; 22/266 public Complex getconjugate() { return new Complex(re, -im); public void multiply(complex c) { double newre = re * c.re - im * c.im; double newim = re * c.im + im * c.re; re = newre; im = newim;
Creating and using objects 23/266
Creating and using objects 24/266 Complex c1 = new Complex(3, 2);
Creating and using objects 25/266 Complex c1 = new Complex(3, 2); Complex c2 = new Complex(5, -2);
Creating and using objects 26/266 Complex c1 = new Complex(3, 2); Complex c2 = new Complex(5, -2); c1.multiply(c2);
Creating and using objects 27/266 Complex c1 = new Complex(3, 2); Complex c2 = new Complex(5, -2); c1.multiply(c2); Complex c3 = c1.getconjugate();
Object reference variables (pointers) Consider the following code: Complex c1 = new Complex(3, 2); 28/266 The variable c1 holds a reference to a Complex object. In other programming languages this is called a pointer. Some books state that Java has no pointers, but in fact every object (including arrays) is a pointer.
Object reference variables (pointers) Be careful when creating a copy of a variable. If the variable is a reference to an object, you will only copy the reference, not the value! primitive types: int i = 4; int j = i; j = j + 2; System.out.println("i = " + i); System.out.println("j = " + j); 29/266 i = 4 j = 6
Object reference variables (pointers) Be careful when creating a copy of a variable. If the variable is a reference to an object, you will only copy the reference, not the value! objects: Complex c = new Complex(3, 5); Complex d = c; d.add(new Complex(1, 1)); System.out.println("c.re = " + c.getreal()); System.out.println("d.re = " + d.getreal()); 30/266 c.re = 4.0 d.re = 4.0
Object reference variables (pointers) Be careful when creating a copy of a variable. If the variable is a reference to an object, you will only copy the reference, not the value! arrays: double[] a = {1, 2, 3; double[] b = a; b[2] = 4; System.out.println("a[2] = " + a[2]); System.out.println("b[2] = " + b[2]); System.out.println("a = " + a); System.out.println("b = " + b); a[2] = 4.0 b[2] = 4.0 a = [D@1888759 b = [D@1888759 31/266
Object reference variables (pointers) Be careful when creating a copy of a variable. If the variable is a reference to an object, you will only copy the reference, not the value! Strings: String s = "Hello"; String t = s; t = t + " world!"; System.out.println("s = " + s); System.out.println("t = " + t); s = Hello t = Hello world! Strings are objects, but no methods exist to modify a String object. All methods defined in the String class return a new String object, and so does the + operator. 32/266
The tostring( ) method The tostring( ) method is automatically declared in every object. It returns a String representation of the reference value. The tostring( ) method is invoked automatically when using the System.out.println( ) command: Complex c = new Complex(3, 2); System.out.println(c); 33/266 Complex@5224ee
The tostring( ) method You can override the tostring( ) method to create your own String representation of the object. Put the following code in Complex.java: public String tostring() { return re + " + " + im + "i"; Now the output becomes: 3.0 + 2.0i Overriding methods will be discussed in greater detail later, when dealing with inheritance. 34/266
Constructors Constructors play the role of initialising objects. In the simplest form, they usually initialise the properties of the class (set the state of the object). Differences with methods: constructors must have the same name as the class itself constructors do not have a return type (not even void) constructors are invoked using the new operator when an object is created. 35/266
Multiple constructors A class can have more than one constructor: 36/266
Multiple constructors A class can have more than one constructor: public Complex(double real, double imaginary) { re = real; im = imaginary; 37/266
Multiple constructors A class can have more than one constructor: public Complex(double real, double imaginary) { re = real; im = imaginary; 38/266 public Complex(double real) {
Multiple constructors A class can have more than one constructor: public Complex(double real, double imaginary) { re = real; im = imaginary; 39/266 public Complex(double real) { re = real; im = 0;
Multiple constructors A class can have more than one constructor: public Complex(double real, double imaginary) { re = real; im = imaginary; 40/266 public Complex(double real) { re = real; im = 0; public Complex() { re = 0; im = 0;
Multiple constructors A constructor can invoke another constructor (but only in the first line of the constructor!) public Complex(double real, double imaginary) { re = real; im = imaginary; 41/266 public Complex(double real) { this(real, 0); public Complex() { this(0);
Static variables, constants and methods The properties of the Complex class, re and im, are known as instance variables. An instance variable is tied to a specific instance of the class (object). If you construct the following two complex numbers: Complex c1 = new Complex(5, 6); Complex c2 = new Complex(2, 11); then c1.re equals 5, while c2.re equals 2. If you want all the instances of a class to share data, use static variables (a.k.a. class variables). This means that all objects of the same class are affected if one object changes the value of a static variable. Static variables are mostly used for constants and common class properties. 42/266
Static variables, constants and methods A typical example of a static variable, is a variable that keeps track of the number of objects of a certain class that have been created. private static int numofobjects = 0; 43/266 public Complex(double real, double imaginary) { re = real; im = imaginary; numofobjects++;
Static variables, constants and methods 44/266 Complex c1 = new Complex(3, 2); Complex c2 = new Complex(5, -2); // c1.numofobjects = 2 // c2.numofobjects = 2 Instead of referring to c1.numofobjects, it is more comprehensible to refer to Complex.numOfObjects. This stresses that numofobjects is a class variable instead of an instance variable. In the same way we can create static methods: public static int getnumberofobjects() { return numofobjects; Usage: System.out.println(Complex.getNumberOfObjects());
Static variables, constants and methods Sometimes a static method can be used instead of a constructor, to create an object of the specified class. Example: suppose you would like to create a complex number given radius (modulus) r and argument (angle) φ: z = re iφ But we already have a constructor Complex(double, double). Solution: public static Complex polar(double r, double phi) { double re = r * Math.cos(phi); double im = r * Math.sin(phi); return new Complex(re, im); 45/266 Usage: Complex c3 = Complex.polar(3, Math.PI / 4);
Static variables, constants and methods The most common usage of static variables is to declare class related constants: public static final Complex I = new Complex(0, 1); 46/266 Usage: Complex c1 = new Complex(3, 2); c1.multiply(complex.i);
UML Class Diagram 47/266 + F A N 1 + F A N E @ K > A H A @ K > A = > I @ K > A = @ @ + F A N L E @ = H C @ K > A + F A N + F A N @ K > A + F A N @ K > A @ K > A C A J + K C = J A + F A N F = H @ K > A @ K > A + F A N I K > J H =? J + F A N L E @
The Math class The Java class Math is a typical class which only defines static methods and properties, and has no constructor. Examples: double d1 = 1.5 * Math.PI; double d2 = Math.sin(d1); double d3 = Math.max(d1, d2); int i = Math.round((float) d3); For a complete list of the methods defined in Math, see the Java documentation. 48/266
The scope of variables The scope of a variable is the block in which it is declared. Outside this block, the variable cannot be used. The following code will give a compiler error: double a = Math.random(); if (a < 0.5) { int i = -1; else { int i = 1; System.out.println("i = " + i); ScopeError.java:103: cannot find symbol symbol : variable i System.out.println("i = " + i); ^ 49/266
The scope of variables The scope of a variable is the block in which it is declared. Outside this block, the variable cannot be used. This is correct: double a = Math.random(); int i; if (a < 0.5) { i = -1; else { i = 1; System.out.println("i = " + i); 50/266
The scope of variables The scope of a variable is the block in which it is declared. Outside this block, the variable cannot be used. Initialising the variable with the else -value is even shorter: double a = Math.random(); int i = 1; if (a < 0.5) { i = -1; System.out.println("i = " + i); 51/266
The scope of variables Class properties are accessible within the whole class block. It is possible, however, to create variables with the same name within a method. In this case a new, local variable will be declared. public class VariableScopeExample { 52/266 private int i; public VariableScopeExample() { i = 4; public void printi() { System.out.println("i = " + i);
The scope of variables Now consider the following methods: 53/266
The scope of variables Now consider the following methods: public void function1(int j) { int i = j; 54/266
The scope of variables Now consider the following methods: public void function1(int j) { int i = j; 55/266 public void function2(int j) { i = j;
The scope of variables Now consider the following methods: public void function1(int j) { int i = j; 56/266 public void function2(int j) { i = j; public void function3(int i) { i = i + 3;
The scope of variables Now consider the following methods: public void function1(int j) { int i = j; 57/266 public void function2(int j) { i = j; public void function3(int i) { i = i + 3; public void function4(int i) { this.i = i + 3;
The scope of variables Now consider the following methods: public static void main(string[] arg) { VariableScopeExample v =new VariableScopeExample(); v.printi(); v.function1(2); v.printi(); v.function2(3); v.printi(); v.function3(4); v.printi(); v.function4(5); v.printi(); 58/266
The scope of variables Now consider the following methods: public static void main(string[] arg) { VariableScopeExample v =new VariableScopeExample(); v.printi(); // i = 4 v.function1(2); v.printi(); v.function2(3); v.printi(); v.function3(4); v.printi(); v.function4(5); v.printi(); 59/266
The scope of variables Now consider the following methods: public static void main(string[] arg) { VariableScopeExample v =new VariableScopeExample(); v.printi(); // i = 4 v.function1(2); v.printi(); // i = 4 v.function2(3); v.printi(); v.function3(4); v.printi(); v.function4(5); v.printi(); 60/266
The scope of variables Now consider the following methods: public static void main(string[] arg) { VariableScopeExample v =new VariableScopeExample(); v.printi(); // i = 4 v.function1(2); v.printi(); // i = 4 v.function2(3); v.printi(); // i = 3 v.function3(4); v.printi(); v.function4(5); v.printi(); 61/266
The scope of variables Now consider the following methods: public static void main(string[] arg) { VariableScopeExample v =new VariableScopeExample(); v.printi(); // i = 4 v.function1(2); v.printi(); // i = 4 v.function2(3); v.printi(); // i = 3 v.function3(4); v.printi(); // i = 3 v.function4(5); v.printi(); 62/266
The scope of variables Now consider the following methods: public static void main(string[] arg) { VariableScopeExample v =new VariableScopeExample(); v.printi(); // i = 4 v.function1(2); v.printi(); // i = 4 v.function2(3); v.printi(); // i = 3 v.function3(4); v.printi(); // i = 3 v.function4(5); v.printi(); // i = 8 63/266
Frequently made mistake in Constructors Correct: private double xpos, ypos, width, length; 64/266 public Rectangle(double xpos, double ypos, double width, double length) { this.xpos = xpos; this.ypos = ypos; this.width = width; this.length = length;
Frequently made mistake in Constructors Also correct: private double xpos, ypos, width, length; 65/266 public Rectangle(double x, double y, double w, double l) { this.xpos = x; this.ypos = y; this.width = w; this.length = l;
Frequently made mistake in Constructors Still correct: private double xpos, ypos, width, length; 66/266 public Rectangle(double x, double y, double w, double l) { xpos = x; ypos = y; width = w; length = l;
Frequently made mistake in Constructors Wrong: private double xpos, ypos, width, length; 67/266 public Rectangle(double x, double y, double w, double l) { double xpos = x; double ypos = y; double width = w; double length = l; New local variables xpos, ypos, width and length will be created, while the properties are unchanged (still 0). Of course this mistake can also be made outside constructors.
2. Class Inheritance and Interfaces Object oriented programming allows you to derive new classes from existing classes. This is called inheritance. If class c2 is derived from another class c1, then we call c1 the superclass and c2 the subclass (or child class, extended class, derived class). A subclass inherits all methods and properties of the superclass. Subclasses are usually extended to contain more functions and/or properties than their superclasses. Every Java class inherits from the class Object. This class defines methods like clone( ), tostring( ). 68/266
A class 69/266 4 A? J = C A A C J D @ K > A M E @ J D @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A 4 A? J = C A @ K > A @ K > A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @
Java source: Rectangle.java 70/266 public class Rectangle { private double xpos; private double ypos; private double width; private double length; public Rectangle(double xpos, double ypos, double width, double length) { this.xpos = xpos; this.ypos = ypos; this.width = width; this.length = length;
Java source: Rectangle.java (part 2) 71/266 public void translate(double dx, double dy) { xpos += dx; ypos += dy; public double calculateperimeter() { return 2*width + 2*length; public double calculatearea() { return width*length;
Using the class 72/266 Rectangle r = new Rectangle(0, 0, 20, 10); r.translate(3, 2); double area = r.area();
Multiple Constructors 73/266 public Rectangle(double xpos, double ypos, double width, double length) { this.xpos = xpos; this.ypos = ypos; this.width = width; this.length = length;
Multiple Constructors 74/266 public Rectangle(double xpos, double ypos, double width, double length) { this.xpos = xpos; this.ypos = ypos; this.width = width; this.length = length; public Rectangle(double width, double length) { this.xpos = 0; this.ypos = 0; this.width = width; this.length = length;
Multiple Constructors 75/266 public Rectangle(double xpos, double ypos, double width, double length) { this.xpos = xpos; this.ypos = ypos; this.width = width; this.length = length; public Rectangle(double width, double length) { this(0, 0, width, length);
More classes 76/266 + E H? A H = @ E K I @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A + E H? A @ K > A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @
Java source: Circle.java 77/266 public class Circle { private double xpos; private double ypos; private double radius; public Circle(double radius) { this(0, 0, radius); public Circle(double xpos, double ypos, double radius) { this.xpos = xpos; this.ypos = ypos; this.radius = radius;
Java source: Circle.java (part 2) 78/266 public void translate(double dx, double dy) { xpos += dx; ypos += dy; public double calculateperimeter() { return 2*Math.PI*radius; public double calculatearea() { return Math.PI*radius*radius;
More classes 79/266 5 G K = H A A C J D @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A 5 G K = H A @ K > A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @
Java source: Square.java 80/266 public class Square { private double xpos; private double ypos; private double length; public Square(double length) { this(0, 0, length); public Square(double xpos, double ypos, double length) { this.xpos = xpos; this.ypos = ypos; this.length = length;
Java source: Square.java (part 2) 81/266 public void translate(double dx, double dy) { xpos += dx; ypos += dy; public double calculateperimeter() { return 4*length; public double calculatearea() { return length*length;
More classes 82/266 6 H E = C A I E @ A @ K > A I E @ A @ K > A I E @ A! @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A J H = I = J A @ K > A @ K > A L E @ 6 H E = C A @ K > A @ K > A @ K > A @ K > A @ K > A
Java source: Triangle.java 83/266 public class Triangle { private double xpos; private double ypos; private double side1; private double side2; private double side3; public Triangle(double xpos, double ypos, double side1, double side2, double side3) { this.xpos = xpos; this.ypos = ypos; this.side1 = side1; this.side2 = side2; this.side3 = side3;
Java source: Triangle.java (part 2) 84/266 public void translate(double dx, double dy) { xpos += dx; ypos += dy; public double calculateperimeter() { return side1 + side2 + side3; public double calculatearea() { double s = calculateperimeter()/2; // Heron of Alexandria s formula return Math.sqrt(s*(s-side1)*(s-side2)*(s-side3));
Problems in current implementation: 85/266 1. method translate(dx, dy) is implemented in the exact same way in all classes. Disadvantages: if you want to change the implementation you should modify all classes you have to implement it again for each new shape 2. although all classes have the methods translate(dx, dy), calculatearea() and calculateperimeter(), you cannot use code like this: Object[] shapes = {new Circle(7), new Rectangle(6, 2), new Triangle(5, 5, 3), new Square(10); double totalarea = 0; for (int i = 0; i < shapes.length; i++) totalarea += shapes[i].calculatearea();
Inheritance Solution: Inheritance. We define a superclass Shape. Objects are defined in terms of classes. 86/266 Rectangle rect = new Rectangle(30, 15); Inheritance defines classes in terms of other classes.
87/266 4 A? J = C A A C J D @ K > A M E @ J D @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A 4 A? J = C A @ K > A @ K > A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ + E H? A H = @ E K I @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A + E H? A @ K > A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ 5 G K = H A A C J D @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A 5 G K = H A @ K > A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ 6 H E = C A I E @ A @ K > A I E @ A @ K > A I E @ A! @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A J H = I = J A @ K > A @ K > A L E @ 6 H E = C A @ K > A @ K > A @ K > A @ K > A @ K > A
88/266 5 D = F A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A 5 D = F A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ 4 A? J = C A A C J D @ K > A M E @ J D @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A 4 A? J = C A @ K > A @ K > A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ + E H? A H = @ E K I @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A + E H? A @ K > A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ 5 G K = H A A C J D @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A 5 G K = H A @ K > A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ 6 H E = C A I E @ A @ K > A I E @ A @ K > A I E @ A! @ K > A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A J H = I = J A @ K > A @ K > A L E @ 6 H E = C A @ K > A @ K > A @ K > A @ K > A @ K > A
89/266 5 D = F A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A 5 D = F A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ A C J D @ K > A M E @ J D @ K > A 4 A? J = C A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A 4 A? J = C A @ K > A @ K > A @ K > A @ K > A H = @ E K I @ K > A + E H? A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A + E H? A @ K > A @ K > A @ K > A A C J D @ K > A M E @ J D @ K > A 5 G K = H A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A 5 G K = H A @ K > A @ K > A @ K > A I E @ A @ K > A I E @ A @ K > A I E @ A! @ K > A 6 H E = C A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A 6 H E = C A @ K > A @ K > A @ K > A @ K > A @ K > A
Java implementation: Shape.java 90/266 public class Shape {
Java implementation: Shape.java 91/266 public abstract class Shape {
Java implementation: Shape.java 92/266 public abstract class Shape { private double xpos, ypos;
Java implementation: Shape.java 93/266 public abstract class Shape { protected double xpos, ypos;
Java implementation: Shape.java 94/266 public abstract class Shape { protected double xpos, ypos; public Shape(double xpos, double ypos) {
Java implementation: Shape.java 95/266 public abstract class Shape { protected double xpos, ypos; public Shape(double xpos, double ypos) { public void translate(double dx, double dy); public double calculateperimeter(); public double calculatearea();
Java implementation: Shape.java 96/266 public abstract class Shape { protected double xpos, ypos; public Shape(double xpos, double ypos) { this.xpos = xpos; this.ypos = ypos; public void translate(double dx, double dy); public double calculateperimeter(); public double calculatearea();
Java implementation: Shape.java 97/266 public abstract class Shape { protected double xpos, ypos; public Shape(double xpos, double ypos) { this.xpos = xpos; this.ypos = ypos; public void translate(double dx, double dy) { xpos += dx; ypos += dy; public double calculateperimeter(); public double calculatearea();
Java implementation: Shape.java 98/266 public abstract class Shape { protected double xpos, ypos; public Shape(double xpos, double ypos) { this.xpos = xpos; this.ypos = ypos; public void translate(double dx, double dy) { xpos += dx; ypos += dy; public abstract double calculateperimeter(); public abstract double calculatearea();
Java implementation: Circle.java 99/266 public class Circle {
Java implementation: Circle.java 100/266 public class Circle extends Shape {
Java implementation: Circle.java 101/266 public class Circle extends Shape { private double radius;
Java implementation: Circle.java 102/266 public class Circle extends Shape { protected double radius;
Java implementation: Circle.java 103/266 public class Circle extends Shape { protected double radius; public Circle(double radius) {
Java implementation: Circle.java 104/266 public class Circle extends Shape { protected double radius; public Circle(double radius) { public Circle(double xpos, double ypos, double radius) {
Java implementation: Circle.java 105/266 public class Circle extends Shape { protected double radius; public Circle(double radius) { this(0, 0, radius); public Circle(double xpos, double ypos, double radius) {
Java implementation: Circle.java 106/266 public class Circle extends Shape { protected double radius; public Circle(double radius) { this(0, 0, radius); public Circle(double xpos, double ypos, double radius) { this.radius = radius;
Java implementation: Circle.java 107/266 public class Circle extends Shape { protected double radius; public Circle(double radius) { this(0, 0, radius); public Circle(double xpos, double ypos, double radius) { super(xpos, ypos) this.radius = radius;
Java implementation: Circle.java (Part 2) 108/266 public double calculateperimeter() { return 2*Math.PI*radius; public double calculatearea() { return Math.PI*radius*radius;
Compatibility of Superclass and Subclass 109/266 Object[] shapes = {new Circle(7), new Rectangle(6, 2), new Triangle(5, 5, 3), new Square(10); double totalarea = 0; for (int i = 0; i < shapes.length; i++) totalarea += shapes[i].calculatearea();
Compatibility of Superclass and Subclass 110/266 Shape[] shapes = {new Circle(7), new Rectangle(6, 2), new Triangle(5, 5, 3), new Square(10); double totalarea = 0; for (int i = 0; i < shapes.length; i++) totalarea += shapes[i].calculatearea();
111/266 5 D = F A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A 5 D = F A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ A C J D @ K > A M E @ J D @ K > A 4 A? J = C A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A 4 A? J = C A @ K > A @ K > A @ K > A @ K > A H = @ E K I @ K > A + E H? A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A + E H? A @ K > A @ K > A @ K > A A C J D @ K > A 5 G K = H A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A 5 G K = H A @ K > A @ K > A @ K > A I E @ A @ K > A I E @ A @ K > A I E @ A! @ K > A 6 H E = C A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A 6 H E = C A @ K > A @ K > A @ K > A @ K > A @ K > A
112/266 5 D = F A N F I @ K > A O F I @ K > A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A 5 D = F A @ K > A @ K > A J H = I = J A @ K > A @ K > A L E @ A C J D @ K > A M E @ J D @ K > A 4 A? J = C A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A 4 A? J = C A @ K > A @ K > A @ K > A @ K > A H = @ E K I @ K > A + E H? A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E E J A H @ K > A + E H? A @ K > A @ K > A @ K > A I E @ A @ K > A I E @ A @ K > A I E @ A! @ K > A 6 H E = C A? =? K = J A ) H A = @ K > A? =? K = J A 2 A H E A J A H @ K > A 6 H E = C A @ K > A @ K > A @ K > A @ K > A @ K > A 5 G K = H A 5 G K = H A @ K > A @ K > A @ K > A
Square.java public class Square extends Rectangle { 113/266 public Square(double length) { this(0, 0, length); public Square(double xpos, double ypos, double length) { super(xpos, ypos, length, length);
Interfaces 114/266 An abstract class with only abstract properties and methods is called an interface. An interface will never have a constructor. public interface Drawable { public abstract void draw(graphics g); Java does not support multiple inheritance (inheriting from more than one class at once), but a class can inherit from multiple interfaces. Inheriting from an interface is called implementing : public class DrawableRectangle extends Rectangle implements Drawable { public void draw(graphics g) { g.drawrect(xpos, ypos, width, length);
Accessibility 115/266 The following modifiers specify the accessibility of a class, property or method: private only accessible by the current class. protected only accessible by the current class, subclasses that extend the current class and all other classes that are part of the same package. public final static accessible by all other classes. object or type can never be changed after the initialisation. Mostly used to specify constants. the property or method can be accessed without having to create an instance of the current class.
3. Some Predefined Java Classes 116/266 Java has a huge number of predefined classes that can be used to build applications. These classes are grouped into packages that provide a convenient way to organise them. You can put the classes you have developed into packages and distribute them to other people. Think of packages as libraries to be shared by many users. You have already seen classes like String, Integer, Double, Math. These classes are all part of the java.lang package. All classes that are part of this package are loaded by default. Classes from other packages must be imported. Until now we have only seen the class JOptionPane which is part of the javax.swing package.
The Java Application Program Interface (API) 117/266 The Java API consists of numerous classes and interfaces grouped into many core packages. The most important are: java.lang awt contains all core Java classes, such as System, Math, Object, String, Number, Boolean, Integer, Float, Double. contains all classes for drawing geometrical figures and (ancient) user interface components, such as Frame, Window, Button, Menu, Font, Graphics. java.awt.event contains classes for handling events, such as MouseEvent, MouseListener, KeyEvent. javax.swing java.applet contains all modern user interface components, such as JFrame, JWindow, JButton, JTextField, JOptionPane. contains classes for supporting applets, such as Applet.
The Java Application Program Interface (API) 118/266 java.io contains classes for input and output streams and files, such as File, FileReader, PrintWriter. java.util contains many utilities, such as Date, Calendar, Vector, Set, Random. java.text contains classes for formatting information, such as date and time. java.net contains classes for supporting network communications, such as URL. You can browse the Java Documentation to see the documentation on all classes and packages.
The String class 119/266 The java.lang.string class has several constructors, but the most frequently used is the special notation using quotes: String welcometext = "Hello World!"; The constructor which has an array of character as argument, can also be used: char[] chararray = new char[26]; for (int i = 0; i < chararray.length; i++) { chararray[i] = (char) ( A + i); String abc = new String(charArray); System.out.println(abc);
The String class Some other useful methods are indexof(string), length( ), equals( ): abc == "ABCDEFGHIJKLMNOPQRSTUVWXYZ" abc.equals("abcdefghijklmnopqrstuvwxyz") abc.equalsignorecase("abcdefghijklmnopqrstuvwxyz") abc.substring(18, 21) abc.substring(abc.length() - 3) abc.indexof("g") abc.indexof("m") 120/266 false true true STU XYZ 6-1
Resizable array: java.util.vector 121/266 The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. Constructor Vector<Type> list = new Vector<Type>(); where Type is a Java class.
122/266 Vector<String> list = new Vector<String>(); Methods list.addelement("hello"); list.insertelementat("world", 0); String s = list.elementat(1); int length = list.size(); Other methods: contains(object), firstelement(), indexof(object), removeelement(object), removeelementat(int)
java.util.vector Please note that you can only insert Objects in a Vector, no primitive types: 123/266
java.util.vector Please note that you can only insert Objects in a Vector, no primitive types: Wrong Vector<int> list2 = new Vector<int>(); list2.addelement(3); 124/266
java.util.vector Please note that you can only insert Objects in a Vector, no primitive types: Right Vector<Integer> list2 = new Vector<Integer>(); list2.addelement(new Integer(3)); int i = list2.elementat(0).intvalue(); 125/266
java.util.vector Please note that you can only insert Objects in a Vector, no primitive types: Also right Vector<Integer> list3 = new Vector<Integer>(); list3.addelement(3); int j = list3.elementat(0); 126/266 Internally Java converts the int to Integer. Since Java 1.5, this is called autoboxing.
Conversion to an Array 127/266 Vector<String> list4 = new Vector<String>(); list4.addelement("hello"); list4.addelement("world"); String[] sarray = new String[list4.size()]; list4.copyinto(sarray);
128/266 4. Object Oriented software development 7 developmental phases in software design: 1. requirements specification 2. system analysis 3. system design 4. implementation 5. testing 6. deployment 7. maintenance Of course when developing mathematical software, the very first step is to develop the algorithm.
Steps in building an object oriented system 129/266 1. identify classes for the system 2. describe attributes and methods in each class 3. establish relationships among classes 4. create classes Three types of relationships: 1. association 2. aggregation 3. inheritance
Relationships among objects: association 130/266 Association is a binary relationship that describes an activity between two classes. The activity can be of any kind, for example "a Student takes a Course", or "a Teacher teaches a Course". An association is usually represented as a data field in the class.
Relationships among objects: aggregation 131/266 Aggregation is a special form of association, in fact the most frequent existing form that represents an ownership relationship between two classes. has a is part of owns Since aggregation is a special form of association, it is also usually represented as a data field in the class.
Relationships among objects: inheritance Inheritance models the "is a" relationship between two classes. strong is-a relationship: direct inheritance between two classes 132/266 extend superclass Example: a Student extends Person weak is-a relationship: class has certain properties implement interface Example: if students can be compared (e.g. on their grades), Student implements Comparable
Inheritance or aggregation 133/266 Sometimes there it is unclear whether a relationship should be "is a" (inheritance) or "has a" (aggregation). Both implementations can be suitable, but depending on the implementation you might have some advantages or disadvantages. Examples: suppose you are implementing the following shape: Is this shape a kind of rectangle, or does is contain one? a graphical rectangle that can be drawn (including colour, location), compared to the geometrical shape rectangle.
= % Case study: linked lists and search trees Array: 134/266! "! # $ "
=! # Case study: linked lists and search trees Linked list: A N J A N J % $ " A N J A N J K 135/266 E A @ E I J A A A J @ K > A A N J E A @ E I J = @ @ - A A J @ K > A L E @ C A J 5 E A E J E I A H J - A A J ) J @ K > A E J L E @ E I - F J O > A = E I = I J - A A J > A = E A @ E I J E A @ E I J @ K > A H A L A - A A J ) J E J L E @ H A L A = I J - A A J L E @
A linked list 136/266 public class LinkedList {
A linked list 137/266 public class LinkedList { protected double element;
A linked list 138/266 public class LinkedList { protected double element; protected LinkedList next;
A linked list 139/266 public class LinkedList { protected double element; protected LinkedList next; public LinkedList() {
A linked list 140/266 public class LinkedList { protected double element; protected LinkedList next; public LinkedList() { this.element = Double.POSITIVE_INFINITY; // empty
A linked list 141/266 public class LinkedList { protected double element; protected LinkedList next; public LinkedList() { this.element = Double.POSITIVE_INFINITY; // empty this.next = null;
A linked list 142/266 public class LinkedList { protected double element; protected LinkedList next; public LinkedList() { this.element = Double.POSITIVE_INFINITY; // empty this.next = null; public LinkedList(double element) { this.element = element; this.next = null;
A linked list 143/266 public boolean isempty() { public boolean islastelement() { public int getsize() {
A linked list 144/266 public boolean isempty() { return element == Double.POSITIVE_INFINITY; public boolean islastelement() { public int getsize() {
A linked list 145/266 public boolean isempty() { return element == Double.POSITIVE_INFINITY; public boolean islastelement() { return next == null; public int getsize() {
A linked list 146/266 public boolean isempty() { return element == Double.POSITIVE_INFINITY; public boolean islastelement() { return next == null; public int getsize() { if (isempty()) return 0;
A linked list 147/266 public boolean isempty() { return element == Double.POSITIVE_INFINITY; public boolean islastelement() { return next == null; public int getsize() { if (isempty()) return 0; else {
A linked list 148/266 public boolean isempty() { return element == Double.POSITIVE_INFINITY; public boolean islastelement() { return next == null; public int getsize() { if (isempty()) return 0; else { if (islastelement()) return 1;
A linked list 149/266 public boolean isempty() { return element == Double.POSITIVE_INFINITY; public boolean islastelement() { return next == null; public int getsize() { if (isempty()) return 0; else { if (islastelement()) return 1; else return 1 + next.getsize();
A linked list 150/266 public void addelement(double element) {
A linked list 151/266 public void addelement(double element) { if (isempty()) this.element = element; else {
A linked list 152/266 public void addelement(double element) { if (isempty()) this.element = element; else { if (islastelement()) { else {
A linked list 153/266 public void addelement(double element) { if (isempty()) this.element = element; else { if (islastelement()) { this.next = new LinkedList(element); else {
A linked list 154/266 public void addelement(double element) { if (isempty()) this.element = element; else { if (islastelement()) { this.next = new LinkedList(element); else { next.addelement(element);
A linked list 155/266 public void removelastelement() {
A linked list 156/266 public void removelastelement() { if (islastelement()) { else {
A linked list 157/266 public void removelastelement() { if (islastelement()) { // only if this is first element in list! element = Double.POSITIVE_INFINITY; else {
A linked list 158/266 public void removelastelement() { if (islastelement()) { // only if this is first element in list! element = Double.POSITIVE_INFINITY; else { if (next.islastelement()) next = null;
A linked list 159/266 public void removelastelement() { if (islastelement()) { // only if this is first element in list! element = Double.POSITIVE_INFINITY; else { if (next.islastelement()) next = null; else next.removelastelement();
A linked list 160/266 public void removeelementat(int index) {
A linked list 161/266 public void removeelementat(int index) { if (index == 0) {
A linked list 162/266 public void removeelementat(int index) { if (index == 0) { if (islastelement())
A linked list 163/266 public void removeelementat(int index) { if (index == 0) { if (islastelement()) element = Double.POSITIVE_INFINITY;
A linked list 164/266 public void removeelementat(int index) { if (index == 0) { if (islastelement()) element = Double.POSITIVE_INFINITY; else {
A linked list 165/266 public void removeelementat(int index) { if (index == 0) { if (islastelement()) element = Double.POSITIVE_INFINITY; else { element = next.element;
A linked list 166/266 public void removeelementat(int index) { if (index == 0) { if (islastelement()) element = Double.POSITIVE_INFINITY; else { element = next.element; next = next.next;
A linked list 167/266 public void removeelementat(int index) { if (index == 0) { if (islastelement()) element = Double.POSITIVE_INFINITY; else { element = next.element; next = next.next; else if (index == 1) {
A linked list 168/266 public void removeelementat(int index) { if (index == 0) { if (islastelement()) element = Double.POSITIVE_INFINITY; else { element = next.element; next = next.next; else if (index == 1) { next = next.next;
A linked list 169/266 public void removeelementat(int index) { if (index == 0) { if (islastelement()) element = Double.POSITIVE_INFINITY; else { element = next.element; next = next.next; else if (index == 1) { next = next.next; else if (index > 1 &&!islastelement()) {
A linked list 170/266 public void removeelementat(int index) { if (index == 0) { if (islastelement()) element = Double.POSITIVE_INFINITY; else { element = next.element; next = next.next; else if (index == 1) { next = next.next; else if (index > 1 &&!islastelement()) { next.removeelementat(index - 1);
A linked list public void insertat(double element, int index) { 171/266
A linked list public void insertat(double element, int index) { if (index == 0) { 172/266
A linked list public void insertat(double element, int index) { if (index == 0) { if (isempty()) this.element = element; else { 173/266
A linked list public void insertat(double element, int index) { if (index == 0) { if (isempty()) this.element = element; else { LinkedList oldnext = next; 174/266
A linked list public void insertat(double element, int index) { if (index == 0) { if (isempty()) this.element = element; else { LinkedList oldnext = next; next = new LinkedList(this.element); 175/266
A linked list public void insertat(double element, int index) { if (index == 0) { if (isempty()) this.element = element; else { LinkedList oldnext = next; next = new LinkedList(this.element); this.element = element; 176/266
A linked list public void insertat(double element, int index) { if (index == 0) { if (isempty()) this.element = element; else { LinkedList oldnext = next; next = new LinkedList(this.element); this.element = element; next.next = oldnext; 177/266
A linked list public void insertat(double element, int index) { if (index == 0) { if (isempty()) this.element = element; else { LinkedList oldnext = next; next = new LinkedList(this.element); this.element = element; next.next = oldnext; else if (index > 0) { 178/266
A linked list public void insertat(double element, int index) { if (index == 0) { if (isempty()) this.element = element; else { LinkedList oldnext = next; next = new LinkedList(this.element); this.element = element; next.next = oldnext; else if (index > 0) { if (islastelement()) next = new LinkedList(element); 179/266
A linked list public void insertat(double element, int index) { if (index == 0) { if (isempty()) this.element = element; else { LinkedList oldnext = next; next = new LinkedList(this.element); this.element = element; next.next = oldnext; else if (index > 0) { if (islastelement()) next = new LinkedList(element); else next.insertelementat(element, index - 1); 180/266
A linked list 181/266 public String tostring() { String s = ""; if (!isempty()) { s = s + " " + element; if (!islastelement()) { return s + next.tostring(); return s;
A linked list 182/266
A linked list 183/266 LinkedList list = new LinkedList(); E I J K
! A linked list 184/266 LinkedList list = new LinkedList(); list.addelement(3.0); E I J K
! # A linked list 185/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); E I J A N J K
! # A linked list 186/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); E I J A N J @ A N J K
!! # A linked list 187/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); E I J A N J @ A N J K K
! # A linked list 188/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); % E I J A N J @ A N J K K
! # A linked list 189/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); % E I J A N J @ A N J K A N J
! # A linked list 190/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); % E I J A N J A N J K
! # A linked list 191/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); list.removelastelement(); % E I J A N J K K
! A linked list 192/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); list.removelastelement(); E I J % A N J K
A linked list 193/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); list.removelastelement(); list.addelement(1.9); %! ' E I J A N J A N J K
! A linked list 194/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); list.removelastelement(); list.addelement(1.9); list.removeelementat(0);! ' E I J A N J A N J K
! A linked list 195/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); list.removelastelement(); list.addelement(1.9); list.removeelementat(0);! ' E I J A N J A N J K
A linked list 196/266 LinkedList list = new LinkedList(); list.addelement(3.0); list.addelement(5.0); list.insertelementat(7.2, 0); list.removelastelement(); list.addelement(1.9); list.removeelementat(0);! ' E I J A N J K
A sorted linked list 197/266
A sorted linked list 198/266 public class SortedLinkedList {
A sorted linked list 199/266 public class SortedLinkedList extends LinkedList {
A sorted linked list 200/266 public class SortedLinkedList extends LinkedList { public SortedLinkedList() { public SortedLinkedList(double element) {
A sorted linked list 201/266 public class SortedLinkedList extends LinkedList { public SortedLinkedList() { super(); public SortedLinkedList(double element) { super(element);
A sorted linked list 202/266 Of course the method insertelementat should be overridden (it cannot be removed since it is automatically inherited from LinkedList. public void insertelementat(double element, int idx) {
A sorted linked list 203/266 Of course the method insertelementat should be overridden (it cannot be removed since it is automatically inherited from LinkedList. public void insertelementat(double element, int idx) { addelement(element);
A sorted linked list 204/266 public void addelement(double element) {
A sorted linked list 205/266 public void addelement(double element) { if (isempty())
A sorted linked list 206/266 public void addelement(double element) { if (isempty()) this.element = element;
A sorted linked list 207/266 public void addelement(double element) { if (isempty()) this.element = element; else {
A sorted linked list 208/266 public void addelement(double element) { if (isempty()) this.element = element; else { if (element < this.element)
A sorted linked list 209/266 public void addelement(double element) { if (isempty()) this.element = element; else { if (element < this.element) super.insertelementat(element, 0);
A sorted linked list 210/266 public void addelement(double element) { if (isempty()) this.element = element; else { if (element < this.element) super.insertelementat(element, 0); else {
A sorted linked list 211/266 public void addelement(double element) { if (isempty()) this.element = element; else { if (element < this.element) super.insertelementat(element, 0); else { if (islastelement()) { else {
A sorted linked list 212/266 public void addelement(double element) { if (isempty()) this.element = element; else { if (element < this.element) super.insertelementat(element, 0); else { if (islastelement()) { this.next = new SortedLinkedList(element); else {
A sorted linked list 213/266 public void addelement(double element) { if (isempty()) this.element = element; else { if (element < this.element) super.insertelementat(element, 0); else { if (islastelement()) { this.next = new SortedLinkedList(element); else { next.addelement(element);
A sorted linked list 214/266 SortedLinkedList list = new SortedLinkedList();
A sorted linked list 215/266 SortedLinkedList list = new SortedLinkedList(); list.addelement(3.0); 3.0
A sorted linked list 216/266 SortedLinkedList list = new SortedLinkedList(); list.addelement(3.0); list.addelement(5.0); 3.0 5.0
A sorted linked list 217/266 SortedLinkedList list = new SortedLinkedList(); list.addelement(3.0); list.addelement(5.0); list.addelement(4.0); 3.0 4.0 5.0
A sorted linked list 218/266 SortedLinkedList list = new SortedLinkedList(); list.addelement(3.0); list.addelement(5.0); list.addelement(4.0); list.insertelementat(7.2, 0); 3.0 4.0 5.0 7.2
A sorted linked list 219/266 SortedLinkedList list = new SortedLinkedList(); list.addelement(3.0); list.addelement(5.0); list.addelement(4.0); list.insertelementat(7.2, 0); list.removelastelement(); 3.0 4.0 5.0
A sorted linked list 220/266 SortedLinkedList list = new SortedLinkedList(); list.addelement(3.0); list.addelement(5.0); list.addelement(4.0); list.insertelementat(7.2, 0); list.removelastelement(); list.addelement(1.9); 1.9 3.0 4.0 5.0
A sorted linked list 221/266 SortedLinkedList list = new SortedLinkedList(); list.addelement(3.0); list.addelement(5.0); list.addelement(4.0); list.insertelementat(7.2, 0); list.removelastelement(); list.addelement(1.9); list.removeelementat(0); 3.0 4.0 5.0
! % & A binary search tree 222/266 A B J H E C D J A B J K A B J H E C D J " K K K K K K Advantage: looking up and storing an element is much faster than in a sorted linked list.
A binary search tree 223/266 We would like to put any object in the tree, not just doubles. But in order to find the correct order, the objects have to be comparable. This way we can determine which object is "less than" the other object. The java.lang.comparable interface: This interface contains one method: compareto(object). It returns an integer that defines the comparison (the distance) between the two object. Classes like Double, Integer, String implement this interface.
A binary search tree 224/266 public class BinarySearchTree { protected Comparable root; protected BinarySearchTree left; protected BinarySearchTree right; public BinarySearchTree() { public BinarySearchTree(Comparable item) {
A binary search tree 225/266 public class BinarySearchTree { protected Comparable root; protected BinarySearchTree left; protected BinarySearchTree right; public BinarySearchTree() { this.left = null; this.right = null; this.root = null; public BinarySearchTree(Comparable item) {
A binary search tree 226/266 public class BinarySearchTree { protected Comparable root; protected BinarySearchTree left; protected BinarySearchTree right; public BinarySearchTree() { this.left = null; this.right = null; this.root = null; public BinarySearchTree(Comparable item) { this(); addelement(item);
A binary search tree 227/266 public boolean isempty() { public Comparable getsmallestelement() {
A binary search tree 228/266 public boolean isempty() { return root == null; public Comparable getsmallestelement() {
A binary search tree 229/266 public boolean isempty() { return root == null; public Comparable getsmallestelement() { if (left == null) { else {
A binary search tree 230/266 public boolean isempty() { return root == null; public Comparable getsmallestelement() { if (left == null) { return root; else {
A binary search tree 231/266 public boolean isempty() { return root == null; public Comparable getsmallestelement() { if (left == null) { return root; else { return left.getsmallestelement();
A binary search tree 232/266 public void addelement(comparable element) {
A binary search tree 233/266 public void addelement(comparable element) { if (isempty())
A binary search tree 234/266 public void addelement(comparable element) { if (isempty()) this.root = element;
A binary search tree 235/266 public void addelement(comparable element) { if (isempty()) this.root = element; else { if (element.compareto(root) < 0) { else {
A binary search tree 236/266 public void addelement(comparable element) { if (isempty()) this.root = element; else { if (element.compareto(root) < 0) { if (left == null) left = new BinarySearchTree(element); else {
A binary search tree 237/266 public void addelement(comparable element) { if (isempty()) this.root = element; else { if (element.compareto(root) < 0) { if (left == null) left = new BinarySearchTree(element); else left.addelement(element); else {
A binary search tree 238/266 public void addelement(comparable element) { if (isempty()) this.root = element; else { if (element.compareto(root) < 0) { if (left == null) left = new BinarySearchTree(element); else left.addelement(element); else { if (right == null) right = new BinarySearchTree(element);
A binary search tree 239/266 public void addelement(comparable element) { if (isempty()) this.root = element; else { if (element.compareto(root) < 0) { if (left == null) left = new BinarySearchTree(element); else left.addelement(element); else { if (right == null) right = new BinarySearchTree(element); else right.addelement(element);
A binary search tree 240/266 public void removesmallestelement() {
A binary search tree 241/266 public void removesmallestelement() { if (left == null) {
A binary search tree 242/266 public void removesmallestelement() { if (left == null) { if (right!= null) {
A binary search tree 243/266 public void removesmallestelement() { if (left == null) { if (right!= null) { root = right.root; left = right.left; right = right.right;
A binary search tree 244/266 public void removesmallestelement() { if (left == null) { if (right!= null) { root = right.root; left = right.left; right = right.right; else root = null;
A binary search tree 245/266 public void removesmallestelement() { if (left == null) { if (right!= null) { root = right.root; left = right.left; right = right.right; else root = null; else if (left.left == null && left.right == null) {
A binary search tree 246/266 public void removesmallestelement() { if (left == null) { if (right!= null) { root = right.root; left = right.left; right = right.right; else root = null; else if (left.left == null && left.right == null) { left = null;
A binary search tree 247/266 public void removesmallestelement() { if (left == null) { if (right!= null) { root = right.root; left = right.left; right = right.right; else root = null; else if (left.left == null && left.right == null) { left = null; else { left.removesmallestelement();
A binary search tree 248/266 public void removelargestelement() {
A binary search tree 249/266 public void removelargestelement() { if (right == null) { if (left!= null) { root = left.root; right = left.right; left = left.left; else root = null; else if (right.left == null && right.right == null) right = null; else { right.removelargestelement();
A binary search tree 250/266 public int getsize() { int n = 0; if (this.root!= null) n++; if (left!= null) n += left.getsize(); if (right!= null) n += right.getsize(); return n; public String tostring() { String s = ""; if (left!= null) s += left.tostring(); if (root!= null) s += " " + root; if (right!= null) s += right.tostring(); return s;
A binary search tree Advantage: 251/266 storing and retrieving an element from a binary search tree is very fast (order log n compared to order n) especially suitable for huge lists Disdvantages: recursive methods are used to traverse the tree, which requires more memory than sequential methods it is difficult to retrieve the n-th element from the tree.
A binary search tree 252/266 BinarySearchTree list = new BinarySearchTree(); list.addelement(3.0); list.addelement(5.0); list.addelement(4.0); list.addelement(7.2); list.removelargestelement(); list.addelement(1.9); list.removelargestelement(); list.removesmallestelement(); list.removesmallestelement();
A binary search tree 253/266 BinarySearchTree list = new BinarySearchTree(); K K K
! A binary search tree 254/266 list.addelement(3.0); K K
! # A binary search tree 255/266 list.addelement(5.0); K H E C D J K K
! " # A binary search tree 256/266 list.addelement(4.0); K H E C D J A B J K K K
! # A binary search tree 257/266 list.addelement(7.2); K H E C D J A B J H E C D J " % K K K K
! # A binary search tree 258/266 list.removelargestelement(); K H E C D J A B J K " % K K K K
! " # A binary search tree 259/266 list.removelargestelement(); K H E C D J A B J K K K
! " # A binary search tree 260/266 list.addelement(1.9); A B J H E C D J ' K K A B J K K K
! " " A binary search tree 261/266 list.removelargestelement(); A B J H E C D J ' K K K K K K
! " A binary search tree 262/266 list.removelargestelement(); A B J H E C D J ' K K K K
! " A binary search tree 263/266 list.removesmallestelement(); K H E C D J ' K K K K
! " A binary search tree 264/266 list.removesmallestelement(); K H E C D J K K
" " A binary search tree 265/266 list.removesmallestelement(); K K K K
" A binary search tree 266/266 list.removesmallestelement(); K K