i219 Software Design Methodology
4. Object‐oriented
programming language 1
Kazuhiro Ogata (JAIST)

2

Outline of lecture• Hello world!
• Class• Inheritance• Interface• Exception• Exception handling• Type cast3

Hello world! (1)public & static method that
returns nothing (void)array of strings
public class HelloWorld {class System public static void main(String[] args) { a String
System.out.println("Hello world!"); } }prints a String and terminates the line
standard output(System’s static field (attribute) (PrintStream’s method that returns
whose type (class) is PrintStream) nothing)modifierclass

 A Java application starts with main(…).
Each application needs to have a class inwhich public static void main(String[] args)
is declared.
 The naming convention for files: eachclass C is written in one class file whosename is C.java.

% javac HelloWorld.java% java HelloWorld
Hello world!
%

4

Hello world! (2)• A class diagram of HelloWorld
root of Javaclass hierarchy

5Class (1)
• A class ClassName is declared as follows:
fields (attributes), methods, constructors, etc.
are declaredcModifiers class ClassName { … }can be accessed from everywhere

the class cannot be extended(cannot have any subclases)

 cModifiers ::= [public] [abstract] [final] …

can be accessed in the
package of the class if
public is not given

Example:abstract class from which no object is madepublic class Point { … }6Class (2)
• A field (attribute) fieldName is declared as follows:
explained later
the result of evaluating this expression isa reference type (class and interface)
used to initialize the field& a primitive type, such as int

fModifiers type fieldName [= initializer ] ;all classes can access the field
if the class is public

only the class in which the field is declared
explained later fModifiers ::= [public|protected|private] [static] [final] …

some classes such as subclasses

if none of the three access modifiers is given,classes in the same package in which the class is

If initializer is omitted, a non‐primitive type (a reference type), integer and double
fields are initialized as null, 0 and +0.0, respectively.

Example:private double x = –0.5 ;
private double y;7Class (3)• A method methodName is declared (defined) as follows
mModifiers type methodName (parameters) methodBody
method signature
The same access control effects
as those to fields

the method cannot be
overridden in its subclasses

 mModifiers ::= [public|protected|private] [abstract] [static] [final] …

parameter type

explained laterparameter name no implementation

 parameters ::= t1 p1, …, tn pn

a sequence of statements such as assignments & return statements
 methodBody ::= ; (if abstract is used) | { … } (otherwise)

Example:public final double getX( ) { return x; }public final void setX(double x) { this.x = x; }attribute x of the object executing setX is set to parameter x

8Class (4)instance variable in Smalltalk• Static fields (attributes):

Each object of a class has (a copy of) each non‐static field, but
a static field is shared by all objects of the class (and its
n is used to count how many
subclasses). class variable in Smalltalk
Example:private static int n = 0;

• Static methods :class methods in Smalltalk

points have been made; every
time an object of Point ismade, n is incremented.

instance methods in Smalltalk

In a static method, non‐static fields & non‐static methods cannot
be used.
Example: public static int howManyPoints() { return n; }A static method can be invoked through an object of the class, but should be
invoked through the class such as Point.howManyPoints().

9

Class (5)• Objects of a class are made with constructors.
• Constructors are declared in a class whose name isthe same as those in methods
ClassName as follows:

ctrModifiers ClassName (parameters) { … }a sequence of statements, such as assignments & return statements
 ctrModifiers ::= [public|protected|private] …

The same access control effects
as those to fields

a class may have multiple
constructors provided that they
have different parameters
Example:public Point( ) { n++; }If x = x is used instead of this.x = x,argument x is set to argument x and field
x is initialized as the default value (+0.0).

public Point(double x,double y) {this.x = x; this.y = y; n++; }10Class (6)• If any constructors are not explicitly declared in a classClassName, the default constructor is automaticallydeclared:Constructors like this are called non‐arg constructors

ctrModifiers ClassName ( ) { }The same access control modifier as that of the class ClassName• If at least one constructor is explicitly declared in a class,the default constructor is not declared.
Example:If no constructor is explicitly declared in Point, the following
default constructor is automatically declared:
public Point( ) { }11Class (7)Two method signatures m1(P1) and m2(P2) are equal if m1 is thesame as m2 and P1 is equal to P2 up to parameter names.

• p1:t1, …, pn:tn is equal to q1:t’1, …, qm:t’m up to parameternames if and only if n = m and ti = t’i for each i.
• Two methods whose name are the same and parameters
are different can be declared in a class; one is said tooverload the other with each other.
method overloading
public double distance() {return Math.sqrt(x*x+y*y);}public double distance(Point pt) {double tmpx = pt.getX() - x;
double tmpy = pt.getY() - y;return Math.sqrt(tmpx*tmpx+tmpy*tmpy); }• Two methods whose name are the same and parameters
are equal up to parameter names cannot be declared in aclass even though the return types of the two methods aredifferent.

12Class (9)• The rest of the class Point:
public class Point { ...
public final double getY() { return y; }public final void setY(double y) { this.y = y; }The static method sqrt(…) in the class Math is invoked.

public double distance() { return Math.sqrt(x*x+y*y); }a concatenation operation of strings

public String toString() { return "(" + x + "," + y + ")"; }}aString + anObject (or anObject + aString) is the same as (or convertedinto) aString + anObject.toSting() (or anObject.toString() + aString)13

Class (10)prefix unary operator

argument of new• An object of a class is made with new plus a constructor
with parameters if any.
Example: (–0.5,0.0) is made(1.4142135623730951, 1.4142135623730951)
Point p0 = new Point();
is madePoint p1 = new Point(1.4142135623730951,1.4142135623730951);
p0.setX(1.0); 1.0 is set to x in p0 by sending setX(1.0) to p0
p0.setY(1.0); 1.0 is set to y in p0 by sending setY(1.0) to p0
System.out.println(p1.getX()); x in p1 is observed by sending getX() to p1
System.out.println(p1.getY()); y in p1 is observed by sending getY() to p1
System.out.println(p0.distance()); The distances of p0 & p1 are observed
System.out.println(p1.distance()); by sending distance() to p0 & p1.
System.out.println(Point.howManyPoints());

n (#points made) is observed by sending howManyPoint() to Point

14

Class (12)• Let us consider a game such that given two points goal & walker
and one integer maxSteps, you succeed if walker gets to goal byrandomly moving to a next point in maxSteps moves.
this class cannot be extended

public final class RandomWalking { assignments to goal & maxSteps are
private final Point goal;
not allowed once they are initialized
private final int maxSteps;
because of final
private Point walker;
public RandomWalking(double gx, double gy,
double wx, double wy, int max) {goal & maxSteps are initialized
goal = new Point (gx,gy);when an object ofwalker = new Point(wx,wy);
RandomWalking is mademaxSteps = max; }public void startWalking() { … } }assignments to goal & maxSteps are not allowed here

15

Class (13)• startWalking is as follows

modification of the contents is allowed;

public void startWalking( ) {even if uncommented, a compiler does// goal.setX(10.0);
not complain// goal = new Point(0.0,0.0);
assignments are not allowed; if// maxSteps = 10;
uncommented, a compiler complains
int steps = 0;
while (true) {System.out.println("walker: " + walker);if (goal.distance(walker) < 1.0) { … break; } got to goal in maxSteps
if (steps >= maxSteps) { … break; } did not get to goal in maxSteps
double dx = Math.random(); double dy = Math.random();dx = Math.random() > 0.2 ? -dx : dx;
dy = Math.random() > 0.2 ? -dy : dy;
the next point to which walker moves iswalker.move(dx,dy);randomly madesteps++; }16

Inheritance (1)• A class can be extended to make a new class.
• Let us make a class of points in 3D space by extending theclass Point.
PointIn3D cannot be extended

fields, constructors, methods

public final class PointIn3D extends Point { ... }subclass

Point is extended superclass• PointIn3D inherits all fields (attributes) & methods
from Point; some of them cannot be directly accessed,
such as x and y in Point.
A field added:

private double z; cannot be directly accessed but

cannot be directly accessed but
can be with howManyPoints()

can be with getX() and getY()

Each object of PointIn3D has three (copies of) fields x, y, z, and sharen with all other objects of Point & PointIn3D.
not only Point

17

Inheritance (2)A constructor added:
public PointIn3D(double x,double y,double z) {super(x,y); this.z = z; }Point(x,y) in Point is invoked

field z in the object being createdis set to argument z• In an constructor, at most one constructor in either thecurrent class (this(…)) or the super class (super(…)) may
be invoked; this(…) or super(…) should appear at the very
beginning place in the constructor; if this(…) is used, this(…)
should be different from the constructor.
• If neither super(…) nor this(…) is invoked, a non‐arg
constructor such as the default one in the superclass isinvoked; if a non‐arg one is not declared, a compiler complains.

18

Inheritance (3)• A type t' is said to be a subtype of a type t if and only if
one of the following cases is fulfilled:– If t is a class (including an abstract class), then t' extends t(namely that t' is a subclass of t).
– If t is an interface, then t' extends t (namely that t' is asubinterface of t) or t' implements t (namely that t' is aclass (including an abstract class) that implements t).

• The subtype relation is transitive; if t' is a subtype of t
and t'' is a subtype of t', then t'' is a subtype of t.
• A type t is a supertype of a type t' if and only if t' is asubtype of t.
• A subtype t' of a type t can be used at the place where t
can be used, but not vice versa.
An interface will be explained later; it is like a class in which no fields are
declared and all methods are abstract.

19

Inheritance (4)this overrides distance() in Point

A method added:
distance() in Point is invoked
public double distance() {double disIn2D = super.distance( );return Math.sqrt(disIn2D*disIn2D+z*z); }SuperClass…
+m(p1:type1,…, pn:typen): type…
SubClass…
+m(q1:type'1,…, qn:type'n): type'…

m in SubClass is said to override m inSuperClass if and only if typei is thesame as type'i for each i, provided
that type' should be type or a subtypeof type if type is a reference type, andbe type if type is a primitive type;otherwise a compiler complains.

20

Inheritance (5)A method added:

pt, an object of PointIn3D, can be used as anargument of distance( ) in Point because PointIn3D isa subtype of Point.

public double distance(PointIn3D pt) {double disIn2D = super.distance(pt);double tmpz = pt.getZ( ) - z;
return Math.sqrt(disIn2D*disIn2D+tmpz*tmpz); }This method overloads distance() & distance(Point pt) in
Point and distance() in PointIn3D.

21Interface (1)• An interface InterfaceName is declared as follows:

methods, etc. are declared

iModifiers interface InterfaceName { … }can be accessed from everywhere

always abstract; can be omitted
and usually omitted

 iModifiers ::= [public] [abstract] …

can be accessed in the package of the class if
public is not given

Example:public interface PointInterface {double getX();
double getY(); }all methods in interfaces are abstract & public,
which can be omitted and usually omitted

22Interface (2)• An interface is implemented by a class (partially by an
abstract class)an abstract class that implements PointInterface
Example: public abstract class AbstractPoint
implements PointInterface {public abstract double distance( );public double distance(PointInterface pt) {double tmpx = this.getX( ) - pt.getX( );double tmpy = this.getY( ) - pt.getY( );return Math.sqrt(tmpx*tmpx+tmpy*tmpy); } }AbstractPoint has three abstract methods; one is distance( ) and the others
are getX( ) and getY( ) that come from PointInterface• Note that if a class has abstract methods, it should be
abstract.

23Interface (3)polar coordinatesr• Class diagram on points

theta (in radian or degree)

private double r;
private double theta;

distance( ) is abstract

public double distance( ) {return r; }public double distance( ) {return Math.sqrt(x*x+y*y); }public PoinRectangularCoordinates
convertToPoinRectangularCoordinates( ) {…}24

Exception (1)• One possible constructor for PointPolarCoordinatesRadian:public PointPolarCoordinatesRadian(double r, double theta) {this.setR(r); this.setTheta(theta); }What if r is nagative?
One way to deal with such a case is to throw (raise) an exception.
First a class for exceptions warning such a case is declared.
Exception(String msg) is invoked

given by Java library

public class PointException extends Exception {public PointException(String msg) {super(msg); } }Note that Exception can be used for this case, but a specific classthat extends Exception should be made to let users(programmers) know what exception has occurred.

25

Exception (2)• The constructor becomespublic PointPolarCoordinatesRadian(double r, double theta)
throws PointException {if (r < 0.0) {declaration that a PointException may be thrown
throw new PointException("r should not be negative!"); }if (theta < 0.0 || theta > 2.0 * Math.PI) {throw new PointException(…); }a PointException is thrownthis.setR(r); this.setTheta(theta); }if r is negative

If an exception is thrown, the control moves back along thesequence of invoking constructors and methods until the
exception is caught; if the exception is not caught, the application
terminates, letting users know that the exception has occurred.

26

Exception handling (1)• Let us make an application that asks a user to input
two points in Polar Coordinates (where radian is used)and calculate the distance of the two points.

making classes in package java.io array of AbstractPoint
for input & output available
whose length is 2 is made;import java.io.*;but no object ofpublic class DistanceBetweenTwoPoints {AbstractPoint is madepublic static void main(String[] args) throws IOException {int i = 0; String line;
double[] r = new double[2];it decodes bytes read from the
double[] theta = new double[2];standard input into characters
AbstractPoint[] p = new AbstractPoint[2];InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
standard input
System.out.println("Input two points in polar coordinate system");it reads character from the standard input in a buffered way

27

Exception handling (2)it reads a line of text and returns the line

while (i < 2) {excluding a line break as a String
try {it removes white spaces at both sides
System.out.print("r" + i + ": "); of the Stringline = br.readLine().trim();it converts a String line into a double;
r[i] = Double.parseDouble(line); if line does not express a double, such
System.out.print("theta" + i + ": "); as “abc”, a NumberFormatException
line = br.readLine().trim();is thrown
theta[i] = Double.parseDouble(line);p[i] = new PointPolarCoordinatesRadian(r[i],theta[i]);i++; standard errora PointException may be thrown} catch(PointException e) {a PointException is caught
System.err.println(e);} catch(NumberFormatException e) {System.err.println(e); } }a NumberFormatException is caught

28

Type castsince the type of p[j] is AbstractPoint, it is necessary to cast the type to
AbstractPointPolarCoordinate so that convertToRectangularCoordinates can be useddouble dis = p[0].distance(p[1]);AbstractPoint[] q = new AbstractPoint[2];for (int j = 0; j < 2; j++) {AbstractPointPolarCoordinates tmp= (AbstractPointPolarCoordinates) p[j];q[j] = tmp.convertToRectangularCoordinates();}
System.out.println(p[0] + "-->" + p[1] + ": " + dis);
System.out.println(p[0] + ": " + q[0]);System.out.println(p[1] + ": " + q[1]); } }if convertToRectangularCoordinates( ) is sent to p[j], a compiler complains that
AbstractPoint does not have the corresponding method.

29

Summary• Hello world!
• Class• Inheritance• Interface• Exception• Exception handling• Type cast