Block IQ
Marko Boon (marko@win.tue.nl) Jacques Resing (resing@win.tue.nl)
2/266
/
department of mathematics and computer science Block IQ 21. Objects and Classes
2. Class Inheritance and Interfaces 3. Some Predefined Java Classes
4. Object Oriented Software Development
Part II: Object Oriented
Programming
3/266
/
department of mathematics and computer science Block IQ 2Programming techniques (learning curve of someone who learns to program):
1. unstructured programming, 2. procedural programming, 3. modular programming,
4. object-oriented programming.
4/266
/
department of mathematics and computer science Block IQ 2Test.java
class Test {
public static void main(String[] arg) {
double complexRe = 3; double complexIm = 2; double a = Math.sqrt(complexRe*complexRe + complexIm*complexIm); } }
Unstructured Programming
5/266
/
department of mathematics and computer science Block IQ 2Test.java
class Test {
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); }
}
6/266
/
department of mathematics and computer science Block IQ 2Complex.java
class Complex {
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); }
7/266
/
department of mathematics and computer science Block IQ 21.
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 pro-grams 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.
8/266
/
department of mathematics and computer science Block IQ 2An 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.
9/266
/
department of mathematics and computer science Block IQ 2A 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 be-haviours. C o m p l e x - i m : d o u b l e - r e : d o u b l e + a b s ( ) : d o u b l e + a d d ( C o m p l e x ) : v o i d + a r g ( ) : d o u b l e + C o m p l e x ( d o u b l e , d o u b l e ) + g e t C o n j u g a t e ( ) : C o m p l e x + s u b t r a c t ( C o m p l e x ) : v o i d
The methods abs and arg return infor-mation 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.
10/266
/
department of mathematics and computer science Block IQ 2Each classmust have at least one constructor which is used to create objects
of this class. This is wrong:
Complex c; c.re = 3; c.im = 5;
It will result in a compiler error:
11/266
/
department of mathematics and computer science Block IQ 2public class Complex {
}
12/266
/
department of mathematics and computer science Block IQ 2public class Complex {
// properties
// constructor(s)
// methods
}
13/266
/
department of mathematics and computer science Block IQ 2public class Complex {
private double re;
private double im;
// constructor(s)
// methods
}
14/266
/
department of mathematics and computer science Block IQ 2public class Complex {
private double re;
private double im;
public Complex(double real, double imaginary) {
}
// methods
}
15/266
/
department of mathematics and computer science Block IQ 2public class Complex {
private double re;
private double im;
public Complex(double real, double imaginary) {
this.re = real;
this.im = imaginary;
}
// methods
}
16/266
/
department of mathematics and computer science Block IQ 2public 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.
17/266
/
department of mathematics and computer science Block IQ 2Some other methods:
public void add(Complex c) {
}
public Complex getConjugate() { }
public void multiply(Complex c) {
}
18/266
/
department of mathematics and computer science Block IQ 2Some other methods:
public void add(Complex c) { re += c.re;
}
public Complex getConjugate() { }
public void multiply(Complex c) {
}
19/266
/
department of mathematics and computer science Block IQ 2Some other methods:
public void add(Complex c) { re += c.re;
im += c.im; }
public Complex getConjugate() { }
public void multiply(Complex c) {
}
20/266
/
department of mathematics and computer science Block IQ 2Some other methods:
public void add(Complex c) { re += c.re;
im += c.im; }
public Complex getConjugate() {
return new Complex(re, -im); }
public void multiply(Complex c) {
}
21/266
/
department of mathematics and computer science Block IQ 2Some other methods:
public void add(Complex c) { re += c.re;
im += c.im; }
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;
}
22/266
/
department of mathematics and computer science Block IQ 2Some other methods:
public void add(Complex c) { re += c.re;
im += c.im; }
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; }
23/266
/
department of mathematics and computer science Block IQ 224/266
/
department of mathematics and computer science Block IQ 2Complex c1 = new Complex(3, 2);
25/266
/
department of mathematics and computer science Block IQ 2Complex c1 = new Complex(3, 2);
Complex c2 = new Complex(5, -2);
26/266
/
department of mathematics and computer science Block IQ 2Complex c1 = new Complex(3, 2);
Complex c2 = new Complex(5, -2);
c1.multiply(c2);
27/266
/
department of mathematics and computer science Block IQ 2Complex c1 = new Complex(3, 2);
Complex c2 = new Complex(5, -2);
c1.multiply(c2);
Complex c3 = c1.getConjugate();
28/266
/
department of mathematics and computer science Block IQ 2Consider the following code:
Complex c1 = new Complex(3, 2);
The variablec1 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)
29/266
/
department of mathematics and computer science Block IQ 2Be 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); i = 4 j = 6
Object reference variables
(pointers)
30/266
/
department of mathematics and computer science Block IQ 2Be 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());
c.re = 4.0 d.re = 4.0
Object reference variables
(pointers)
31/266
/
department of mathematics and computer science Block IQ 2Be 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
Object reference variables
(pointers)
32/266
/
department of mathematics and computer science Block IQ 2Be 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.
Object reference variables
(pointers)
33/266
/
department of mathematics and computer science Block IQ 2The 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);
Complex@5224ee
34/266
/
department of mathematics and computer science Block IQ 2You can override the toString( ) method to create your own String representa-tion 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.
35/266
/
department of mathematics and computer science Block IQ 2Constructors 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
cre-ated.
36/266
/
department of mathematics and computer science Block IQ 2A class can have more than one constructor:
37/266
/
department of mathematics and computer science Block IQ 2A class can have more than one constructor:
public Complex(double real, double imaginary) { re = real;
im = imaginary; }
38/266
/
department of mathematics and computer science Block IQ 2A class can have more than one constructor:
public Complex(double real, double imaginary) { re = real;
im = imaginary; }
public Complex(double real) {
}
39/266
/
department of mathematics and computer science Block IQ 2A class can have more than one constructor:
public Complex(double real, double imaginary) { re = real;
im = imaginary; }
public Complex(double real) { re = real;
im = 0; }
40/266
/
department of mathematics and computer science Block IQ 2A class can have more than one constructor:
public Complex(double real, double imaginary) { re = real;
im = imaginary; }
public Complex(double real) { re = real; im = 0; } public Complex() { re = 0; im = 0; }
Multiple constructors
41/266
/
department of mathematics and computer science Block IQ 2A constructor can invoke another constructor (but only in the first line of the constructor!)
public Complex(double real, double imaginary) { re = real;
im = imaginary; }
public Complex(double real) {
this(real, 0); } public Complex() { this(0); }
Multiple constructors
42/266
/
department of mathematics and computer science Block IQ 2The properties of the Complex class, re and im, are known as instance
vari-ables. 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, usestatic 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.
Static variables, constants and
methods
43/266
/
department of mathematics and computer science Block IQ 2A 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;
public Complex(double real, double imaginary) { re = real;
im = imaginary; numOfObjects++; }
Static variables, constants and
methods
44/266
/
department of mathematics and computer science Block IQ 2Complex 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
45/266
/
department of mathematics and computer science Block IQ 2Sometimes 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 =r eiφ
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); }
Usage: Complex c3 = Complex.polar(3, Math.PI / 4);
Static variables, constants and
methods
46/266
/
department of mathematics and computer science Block IQ 2The most common usage of static variables is to declare class related con-stants:
public static final Complex I = new Complex(0, 1);
Usage:
Complex c1 = new Complex(3, 2);
c1.multiply(Complex.I);
Static variables, constants and
methods
47/266
/
department of mathematics and computer science Block IQ 2C o m p l e x + I : C o m p l e x - i m : d o u b l e - r e : d o u b l e + a b s ( ) : d o u b l e + a d d ( C o m p l e x ) : v o i d + a r g ( ) : d o u b l e + C o m p l e x ( ) + C o m p l e x ( d o u b l e ) + C o m p l e x ( d o u b l e , d o u b l e ) + g e t C o n j u g a t e ( ) : C o m p l e x + p o l a r ( d o u b l e , d o u b l e ) : C o m p l e x + s u b t r a c t ( C o m p l e x ) : v o i d
48/266
/
department of mathematics and computer science Block IQ 2The 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 documenta-tion.
49/266
/
department of mathematics and computer science Block IQ 2The 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); ^
50/266
/
department of mathematics and computer science Block IQ 2The 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);
51/266
/
department of mathematics and computer science Block IQ 2The 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);
52/266
/
department of mathematics and computer science Block IQ 2Class 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 anew, local variable will be declared.
public class VariableScopeExample {
private int i;
public VariableScopeExample() { i = 4;
}
public void printi() {
System.out.println("i = " + i); }
}
53/266
/
department of mathematics and computer science Block IQ 2Now consider the following methods:
54/266
/
department of mathematics and computer science Block IQ 2Now consider the following methods:
public void function1(int j) {
int i = j;
}
55/266
/
department of mathematics and computer science Block IQ 2Now consider the following methods:
public void function1(int j) {
int i = j;
}
public void function2(int j) { i = j;
}
56/266
/
department of mathematics and computer science Block IQ 2Now consider the following methods:
public void function1(int j) {
int i = j;
}
public void function2(int j) { i = j;
}
public void function3(int i) { i = i + 3;
}
57/266
/
department of mathematics and computer science Block IQ 2Now consider the following methods:
public void function1(int j) {
int i = j;
}
public void function2(int j) { i = j;
}
public void function3(int i) { i = i + 3;
}
public void function4(int i) {
this.i = i + 3;
}
58/266
/
department of mathematics and computer science Block IQ 2Now 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(); }
59/266
/
department of mathematics and computer science Block IQ 2Now 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(); }
60/266
/
department of mathematics and computer science Block IQ 2Now 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(); }
61/266
/
department of mathematics and computer science Block IQ 2Now 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(); }
62/266
/
department of mathematics and computer science Block IQ 2Now 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(); }
63/266
/
department of mathematics and computer science Block IQ 2Now 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 }
64/266
/
department of mathematics and computer science Block IQ 2Correct:
private double xpos, ypos, width, length;
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
65/266
/
department of mathematics and computer science Block IQ 2Also correct:
private double xpos, ypos, width, length;
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
66/266
/
department of mathematics and computer science Block IQ 2Still correct:
private double xpos, ypos, width, length;
public Rectangle(double x, double y,
double w, double l) { xpos = x; ypos = y; width = w; length = l; }
Frequently made mistake in
Constructors
67/266
/
department of mathematics and computer science Block IQ 2Wrong:
private double xpos, ypos, width, length;
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.
Frequently made mistake in
Constructors
68/266
/
department of mathematics and computer science Block IQ 22.
Class Inheritance and Interfaces
Object oriented programming allows you to derive new classes from existing
classes. This is calledinheritance.
If classc2is derived from another classc1, then we callc1thesuperclass and
c2the 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( ).
69/266
/
department of mathematics and computer science Block IQ 2R e c t a n g l e
- l e n g t h : d o u b l e
- w i d t h : d o u b l e
- x p o s : d o u b l e
- y p o s : d o u b l e
+ c a l c u l a t e A r e a ( ) : d o u b l e
+ c a l c u l a t e P e r i m e t e r ( ) : d o u b l e
+ R e c t a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e )
+ t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d
A class
70/266
/
department of mathematics and computer science Block IQ 2public 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;
}
71/266
/
department of mathematics and computer science Block IQ 2public void translate(double dx, double dy) { xpos += dx;
ypos += dy; }
public double calculatePerimeter() {
return 2*width + 2*length;
}
public double calculateArea() {
return width*length;
} }
72/266
/
department of mathematics and computer science Block IQ 2Rectangle r = new Rectangle(0, 0, 20, 10);
r.translate(3, 2);
double area = r.area();
73/266
/
department of mathematics and computer science Block IQ 2public Rectangle(double xpos, double ypos,
double width, double length) {
this.xpos = xpos;
this.ypos = ypos;
this.width = width;
this.length = length;
}
74/266
/
department of mathematics and computer science Block IQ 2public 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;
}
75/266
/
department of mathematics and computer science Block IQ 2public 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);
}
76/266
/
department of mathematics and computer science Block IQ 2C i r c l e - r a d i u s : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + C i r c l e ( d o u b l e , d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d
More classes
77/266
/
department of mathematics and computer science Block IQ 2public 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;
}
78/266
/
department of mathematics and computer science Block IQ 2public 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;
} }
79/266
/
department of mathematics and computer science Block IQ 2S q u a r e - l e n g t h : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + S q u a r e ( d o u b l e , d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d
More classes
80/266
/
department of mathematics and computer science Block IQ 2public 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;
}
81/266
/
department of mathematics and computer science Block IQ 2public void translate(double dx, double dy) { xpos += dx;
ypos += dy; }
public double calculatePerimeter() {
return 4*length;
}
public double calculateArea() {
return length*length;
} }
82/266
/
department of mathematics and computer science Block IQ 2T r i a n g l e - s i d e 1 : d o u b l e - s i d e 2 : d o u b l e - s i d e 3 : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d + T r i a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e , d o u b l e )
More classes
83/266
/
department of mathematics and computer science Block IQ 2public 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;
}
84/266
/
department of mathematics and computer science Block IQ 2public 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));
} }
85/266
/
department of mathematics and computer science Block IQ 2Problems in current implementation:
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(), youcannotuse 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++)
86/266
/
department of mathematics and computer science Block IQ 2Solution: Inheritance. We define a superclass Shape.
Objects are defined in terms of classes.
Rectangle rect = new Rectangle(30, 15);
Inheritance defines classes in terms of other classes.
Inheritance
87/266
/
department of mathematics and computer science Block IQ 2R e c t a n g l e - l e n g t h : d o u b l e - w i d t h : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + R e c t a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d S q u a r e - l e n g t h : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + S q u a r e ( d o u b l e , d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d T r i a n g l e - s i d e 1 : d o u b l e - s i d e 2 : d o u b l e - s i d e 3 : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d + T r i a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e , d o u b l e ) C i r c l e - r a d i u s : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + C i r c l e ( d o u b l e , d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d
88/266
/
department of mathematics and computer science Block IQ 2R e c t a n g l e - l e n g t h : d o u b l e - w i d t h : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + R e c t a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d S q u a r e - l e n g t h : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + S q u a r e ( d o u b l e , d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d T r i a n g l e - s i d e 1 : d o u b l e - s i d e 2 : d o u b l e - s i d e 3 : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d + T r i a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e , d o u b l e ) S h a p e # x p o s : d o u b l e # y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e # S h a p e ( d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d C i r c l e - r a d i u s : d o u b l e - x p o s : d o u b l e - y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + C i r c l e ( d o u b l e , d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d
89/266
/
department of mathematics and computer science Block IQ 2C i r c l e # r a d i u s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e + C i r c l e ( d o u b l e , d o u b l e , d o u b l e ) R e c t a n g l e # l e n g t h : d o u b l e # w i d t h : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e + R e c t a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e ) S h a p e # x p o s : d o u b l e # y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e # S h a p e ( d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d T r i a n g l e # s i d e 1 : d o u b l e # s i d e 2 : d o u b l e # s i d e 3 : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + T r i a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e , d o u b l e ) S q u a r e # l e n g t h : d o u b l e # w i d t h : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e + S q u a r e ( d o u b l e , d o u b l e , d o u b l e )
90/266
/
department of mathematics and computer science Block IQ 2public class Shape {
}
91/266
/
department of mathematics and computer science Block IQ 2public abstract class Shape {
}
92/266
/
department of mathematics and computer science Block IQ 2public abstract class Shape {
private double xpos, ypos;
}
93/266
/
department of mathematics and computer science Block IQ 2public abstract class Shape {
protected double xpos, ypos;
}
94/266
/
department of mathematics and computer science Block IQ 2public abstract class Shape {
protected double xpos, ypos;
public Shape(double xpos, double ypos) {
}
}
95/266
/
department of mathematics and computer science Block IQ 2public 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(); }
96/266
/
department of mathematics and computer science Block IQ 2public 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(); }
97/266
/
department of mathematics and computer science Block IQ 2public 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(); }
98/266
/
department of mathematics and computer science Block IQ 2public 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(); }
99/266
/
department of mathematics and computer science Block IQ 2public class Circle {
100/266
/
department of mathematics and computer science Block IQ 2public class Circle extends Shape {
101/266
/
department of mathematics and computer science Block IQ 2public class Circle extends Shape {
private double radius;
102/266
/
department of mathematics and computer science Block IQ 2public class Circle extends Shape {
protected double radius;
103/266
/
department of mathematics and computer science Block IQ 2public class Circle extends Shape {
protected double radius;
public Circle(double radius) { }
104/266
/
department of mathematics and computer science Block IQ 2public class Circle extends Shape {
protected double radius;
public Circle(double radius) { }
public Circle(double xpos, double ypos,
double radius) {
}
105/266
/
department of mathematics and computer science Block IQ 2public class Circle extends Shape {
protected double radius;
public Circle(double radius) {
this(0, 0, radius);
}
public Circle(double xpos, double ypos,
double radius) {
}
106/266
/
department of mathematics and computer science Block IQ 2public 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;
}
107/266
/
department of mathematics and computer science Block IQ 2public 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;
}
108/266
/
department of mathematics and computer science Block IQ 2public double calculatePerimeter() {
return 2*Math.PI*radius;
}
public double calculateArea() {
return Math.PI*radius*radius;
} }
Java implementation: Circle.java
(Part 2)
109/266
/
department of mathematics and computer science Block IQ 2Object[] 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
/
department of mathematics and computer science Block IQ 2Shape[] 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
111/266
/
department of mathematics and computer science Block IQ 2C i r c l e # r a d i u s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e + C i r c l e ( d o u b l e , d o u b l e , d o u b l e ) R e c t a n g l e # l e n g t h : d o u b l e # w i d t h : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e + R e c t a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e ) S h a p e # x p o s : d o u b l e # y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e # S h a p e ( d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d T r i a n g l e # s i d e 1 : d o u b l e # s i d e 2 : d o u b l e # s i d e 3 : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + T r i a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e , d o u b l e ) S q u a r e # l e n g t h : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e + S q u a r e ( d o u b l e , d o u b l e , d o u b l e )
112/266
/
department of mathematics and computer science Block IQ 2C i r c l e # r a d i u s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e + C i r c l e ( d o u b l e , d o u b l e , d o u b l e ) R e c t a n g l e # l e n g t h : d o u b l e # w i d t h : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e + R e c t a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e ) S h a p e # x p o s : d o u b l e # y p o s : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m i t e r ( ) : d o u b l e # S h a p e ( d o u b l e , d o u b l e ) + t r a n s l a t e ( d o u b l e , d o u b l e ) : v o i d T r i a n g l e # s i d e 1 : d o u b l e # s i d e 2 : d o u b l e # s i d e 3 : d o u b l e + c a l c u l a t e A r e a ( ) : d o u b l e + c a l c u l a t e P e r i m e t e r ( ) : d o u b l e + T r i a n g l e ( d o u b l e , d o u b l e , d o u b l e , d o u b l e , d o u b l e ) S q u a r e + S q u a r e ( d o u b l e , d o u b l e , d o u b l e )
113/266
/
department of mathematics and computer science Block IQ 2Square.java
public class Square extends Rectangle {
public Square(double length) {
this(0, 0, length);
}
public Square(double xpos, double ypos,
double length) {
super(xpos, ypos, length, length); }
114/266
/
department of mathematics and computer science Block IQ 2An abstract class with only abstract properties and methods is called an inter-face. 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); }
}
115/266
/
department of mathematics and computer science Block IQ 2The 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 pack-age.
public accessible by all other classes.
final object or type can never be changed after the initialisation. Mostly
used to specify constants.
static the property or method can be accessed without having to create
an instance of the current class.
116/266
/
department of mathematics and computer science Block IQ 23.
Some Predefined Java Classes
Java has a huge number of predefined classes that can be used to build appli-cations. These classes are grouped into packages that provide a convenient way to organise them. You can put the classes you have developed into pack-ages and distribute them to other people. Think of packpack-ages 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.
117/266
/
department of mathematics and computer science Block IQ 2The Java API consists of numerous classes and interfaces grouped into many core packages. The most important are:
java.lang contains all core Java classes, such as System, Math, Object,
String, Number, Boolean, Integer, Float, Double.
awt contains all classes for drawing geometrical figures and
(an-cient) 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 contains all modern user interface components, such as
JFrame, JWindow, JButton, JTextField, JOptionPane.
java.applet contains classes for supporting applets, such as Applet.
The Java Application Program
Interface (API)
118/266
/
department of mathematics and computer science Block IQ 2java.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,
Ran-dom.
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 Java Application Program
Interface (API)
119/266
/
department of mathematics and computer science Block IQ 2The 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);
120/266
/
department of mathematics and computer science Block IQ 2Some 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") false true true STU XYZ 6 -1
121/266
/
department of mathematics and computer science Block IQ 2The 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>();
whereType is a Java class.
122/266
/
department of mathematics and computer science Block IQ 2Vector<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)
123/266
/
department of mathematics and computer science Block IQ 2Please note that you can only insert Objects in a Vector, no primitive types:
124/266
/
department of mathematics and computer science Block IQ 2Please note that you can only insert Objects in a Vector, no primitive types:
Wrong
Vector<int> list2 = new Vector<int>();
list2.addElement(3);
125/266
/
department of mathematics and computer science Block IQ 2Please 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();
126/266
/
department of mathematics and computer science Block IQ 2Please 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);
Internally Java converts the int to Integer. Since Java 1.5, this is called
autoboxing.
127/266
/
department of mathematics and computer science Block IQ 2Vector<String> list4 = new Vector<String>();
list4.addElement("Hello"); list4.addElement("World");
String[] sArray = new String[list4.size()];
list4.copyInto(sArray);
128/266
/
department of mathematics and computer science Block IQ 24.
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.
129/266
/
department of mathematics and computer science Block IQ 21. 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
Steps in building an object
oriented system
130/266
/
department of mathematics and computer science Block IQ 2Association 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:
association
131/266
/
department of mathematics and computer science Block IQ 2Aggregation 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 repre-sented as a data field in the class.
Relationships among objects:
aggregation
132/266
/
department of mathematics and computer science Block IQ 2Inheritance models the "is a" relationship between two classes.
• strong is-a relationship: direct inheritance between two classes
−→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 im-plements Comparable
Relationships among objects:
inheritance
133/266
/
department of mathematics and computer science Block IQ 2Sometimes there it is unclear whether a relationship should be "is a" (inher-itance) or "has a" (aggregation). Both implementations can be suitable, but depending on the implementation you might have some advantages or disad-vantages.
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),
com-pared to the geometrical shape rectangle.
134/266
/
department of mathematics and computer science Block IQ 2Array:
a
3
0
5
1
7
2
6
3
4
4
Case study: linked lists and search
trees
135/266
/
department of mathematics and computer science Block IQ 2Linked list:
5
a
3
n e x t7
6
4
n u l l n e x t n e x t n e x t L i n k e d L i s t # e l e m e n t : d o u b l e # n e x t : L i n k e d L i s t + a d d E l e m e n t ( d o u b l e ) : v o i d + g e t S i z e ( ) : i n t + i n s e r t E l e m e n t A t ( d o u b l e , i n t ) : v o i d + i s E m p t y ( ) : b o o l e a n + i s L a s t E l e m e n t ( ) : b o o l e a n + L i n k e d L i s t ( ) + L i n k e d L i s t ( d o u b l e ) + r e m o v e E l e m e n t A t ( i n t ) : v o i d + r e m o v e L a s t E l e m e n t ( ) : v o i dCase study: linked lists and search
trees
136/266
/
department of mathematics and computer science Block IQ 2public class LinkedList {
137/266
/
department of mathematics and computer science Block IQ 2public class LinkedList {
protected double element;
138/266
/
department of mathematics and computer science Block IQ 2public class LinkedList {
protected double element;
protected LinkedList next;
139/266
/
department of mathematics and computer science Block IQ 2public class LinkedList {
protected double element;
protected LinkedList next;
public LinkedList() {
}
140/266
/
department of mathematics and computer science Block IQ 2public class LinkedList {
protected double element;
protected LinkedList next;
public LinkedList() {
this.element = Double.POSITIVE_INFINITY; // empty
}
141/266
/
department of mathematics and computer science Block IQ 2public class LinkedList {
protected double element;
protected LinkedList next;
public LinkedList() {
this.element = Double.POSITIVE_INFINITY; // empty
this.next = null;
}
142/266
/
department of mathematics and computer science Block IQ 2public 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;
}
143/266
/
department of mathematics and computer science Block IQ 2public boolean isEmpty() { }
public boolean isLastElement() { }
public int getSize() {
}
14