89
Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information Engineering National Taiwan University Summer 2019

Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Embed Size (px)

Citation preview

Page 1: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Java Programming 2Object-Oriented Programming

Zheng-Liang Lu

Department of Computer Science & Information EngineeringNational Taiwan University

Summer 2019

Page 2: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 class Lecture7 {2

3 // Object−Oriented Programming4

5 }6

7 // Key words:8 class, new, this, static, null, extends, super, abstract, final,

interface, implements, protected

Zheng-Liang Lu Java Programming 2 1 / 88

Page 3: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Object

• An object keeps its own states in fields (attributes) andexposes its behaviors through associated methods.

• For example, describe about your cellphone.• Attributes: battery status, 4G signal strength, phonebook,

album, music, clips, and so on.• Functions? You can name it.

• To create these objects, we collect all attributes associatedwith functions and put them in a new class.

Zheng-Liang Lu Java Programming 2 2 / 88

Page 4: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Class

• Classes are the building blocks in every Java program.

• A class is the blueprint to create class instances, aka runtimeobjects.

• We define a new class as follows:• give a class name with the first letter capitalized, by

convention;• declare data and function members in the class body.

• For example,

1 public class Point {2 // data members3 double x, y;4 }

Zheng-Liang Lu Java Programming 2 3 / 88

Page 5: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Points

1 public class PointDemo {2 public static void main(String[] args) {3

4 // now create a new instance of Point5 Point p1 = new Point();6 p1.x = 1;7 p1.y = 2;8

9 // create another instance of Point10 Point p2 = new Point();11 p2.x = 3;12 p2.y = 4;13

14 System.out.printf("(%.2f, %.2f)\n", p1.x, p1.y);15 System.out.printf("(%.2f, %.2f)\n", p2.x, p2.y);16 }17 }

• Note that a class also acts as a (derived) type.

Zheng-Liang Lu Java Programming 2 4 / 88

Page 6: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Data Members

• Each field may have an access modifier, say public andprivate.

• public: accessible by all classes• private: accessible only within its own class

• In OO paradigm, we hide internal states and expose methodswhich perform actions on these fields.

• So all fields should be declared private.• This is so-called encapsulation.

• However, this private modifier does not quarantine anyinformation security.1

• What private is good for maintainability and modularity.2

1Thanks to a lively discussion on January 23, 2017.2Read http://stackoverflow.com/questions/9201603/

are-private-members-really-more-secure-in-java.Zheng-Liang Lu Java Programming 2 5 / 88

Page 7: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Function Members

• As said, the fields are hidden.

• So we provide getters and setters if necessary:• getter: return the state of the object• setter: set a value to the state of the object

• For example, getX() and getY() are getters; setX() and setY()are setters in the class Point.

Zheng-Liang Lu Java Programming 2 6 / 88

Page 8: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Point (Encapsulated)

1 public class Point {2 // data members: fields or attributes3 private double x;4 private double y;5

6 // function members: methods7 public double getX() { return x; }8 public double getY() { return y; }9

10 public void setX(double new x) { x = new x; }11 public void setY(double new y) { y = new y; }12 }

Zheng-Liang Lu Java Programming 2 7 / 88

Page 9: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Constructors

• A constructor follows the new operator, acting like othermethods.

• However, its names should be identical to the name of theclass and it has no return type.

• A class may have several constructors if needed.• Recall method overloading.

• Note that constructors belong to the class but not objects.• In other words, constructors cannot be invoked by any object.

• If you don’t define any explicit constructor, Java assumes adefault constructor for you.

• Moreover, adding any explicit constructor disables the defaultconstructor.

Zheng-Liang Lu Java Programming 2 8 / 88

Page 10: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Parameterized Constructors

• You can initialize an object when the object is ready.

• For example,

1 public class Point {2 ...3 // default constructor4 public Point() {5 // do something in common6 }7

8 // parameterized constructor9 public Point(double new x, double new y) {

10 x = new x;11 y = new y;12 }13 ...14 }

Zheng-Liang Lu Java Programming 2 9 / 88

Page 11: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Self Reference

• You can refer to any (instance) member of the current objectwithin methods and constructors by using this.

• The most common reason for using the this keyword isbecause a field is shadowed by method parameters.

• Recall the variable scope.

• You can also use this to call another constructor in the sameclass, say this().

Zheng-Liang Lu Java Programming 2 10 / 88

Page 12: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Point (Revisited)

1 public class Point {2 ...3 public Point(double x, double y) {4 this.x = x;5 this.y = y;6 }7 ...8 }

• However, the this operator cannot be used in static methods.

Zheng-Liang Lu Java Programming 2 11 / 88

Page 13: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Instance Members

• Starting from this lecture, all members are declared w/ostatic, so-called instance members.

• These instance members are available only after the object iscreated.

• Semantically, each object has its own states associated withthe accessory methods applying on.

• For example, getX() could be invoked when a specific Pointobject is assigned.

Zheng-Liang Lu Java Programming 2 12 / 88

Page 14: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example

• In OOP design, it is important to clarify the responsibilityamong objects.

1 public class Point {2 ...3 public double getDistanceFrom(Point that) {4 return Math.sqrt(Math.pow(this.x − that.x, 2)5 + Math.pow(this.y − that.y, 2));6 }7 ...8 }

Zheng-Liang Lu Java Programming 2 13 / 88

Page 15: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Static Members

• Static members belong to the class3.

• Those members are ready once the class is loaded.• For example, main().

• They can be invoked directly by the class name without anyinstance.

• For example, Math.PI.

• Static methods act as utility methods that perform workwhich is independent of instances.

• For example, Math.random().

• A static method can access other static members. (Trivial.)

• However, static methods cannot access to instance membersdirectly. (Why?)

3Aka class members.Zheng-Liang Lu Java Programming 2 14 / 88

Page 16: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example

1 public class Point {2 ...3 public static double measure(Point first, Point second) {4 // You cannot use this.x and this.y here!5 return Math.sqrt(Math.pow(first.x − second.x, 2)6 + Math.pow(first.y − second.y, 2));7 }8 ...9 }

1 public class PointDemo {2

3 public static void main(String[] args) {4

5 /∗ ignore the previous codes ∗/6

7 System.out.println(Point.measure(p1, p2));8

9 }10 }

Zheng-Liang Lu Java Programming 2 15 / 88

Page 17: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Another Example: Singleton

• The singleton pattern is one of design patterns.4

• For some situations, you need only one object of this type inthe system.

1 public class Singleton {2

3 // Do now allow to invoke the constructor by other classes.4 private Singleton() {}5

6 // Will be ready as soon as the class is loaded.7 private static Singleton instance = new Singleton();8

9 // Only way to obtain this singleton by the outside world.10 public static Singleton getInstance() {11 return instance;12 }13 }

4Design pattern is a general reusable solution to a commonly occurringproblem within a given context in software design.

Zheng-Liang Lu Java Programming 2 16 / 88

Page 18: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Object Elimination: Garbage Collection (GC)5

• Java handles object deallocation by GC.• Timing: preset period or when memory stress occurs.

• GC is a daemon thread, which searches for those unreferencedobjects.

• An object is unreferenced when it is no longer referenced byany part of your program. (How?)

• To make the object unreferenced, simply assign null to thereference.

• Note that you may invoke System.gc() to execute thedeallocation procedure.

• However, frequent invocation of GC is time-consuming.

5http://www.oracle.com/webfolder/technetwork/tutorials/obe/

java/gc01/index.html

Zheng-Liang Lu Java Programming 2 17 / 88

Page 19: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Unified Modeling Language6

• Unified Modeling Language (UML) is a tool for specifying,visualizing, constructing, and documenting the artifacts ofsoftware systems, as well as for business modeling and othernon-software systems.

• Free software:• http://staruml.io/ (available for all platforms)

6See http://www.tutorialspoint.com/uml/ andhttp://www.mitchellsoftwareengineering.com/IntroToUML.pdf.

Zheng-Liang Lu Java Programming 2 18 / 88

Page 20: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Class Diagram for Point

• Modifiers can be placed before both fields and methods:• + for public• − for private

Zheng-Liang Lu Java Programming 2 19 / 88

Page 21: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

HAS-A Relationship

• Association is a weak relationship where all objects have theirown lifetime and there is no ownership.

• For example, teacher ↔ student; doctor ↔ patient.

• If A uses B, then it is an aggregation, stating that B existsindependently from A.

• For example, knight ↔ sword; company ↔ employee.

• If A owns B, then it is a composition, meaning that B has nomeaning or purpose in the system without A.

• For example, house ↔ room.

Zheng-Liang Lu Java Programming 2 20 / 88

Page 22: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Lines (Aggregation)

• +2: two Point objects used in one Line object.

Zheng-Liang Lu Java Programming 2 21 / 88

Page 23: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 public class Line {2 private Point head, tail;3

4 public Line(Point p1, Point p2) {5 head = p1;6 tail = p2;7 }8

9 /∗ ignore some methods ∗/10

11 public double getLength() {12 return head.getDistanceFrom(tail);13 }14

15 }

Zheng-Liang Lu Java Programming 2 22 / 88

Page 24: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

More Examples

• Circle, Triangle, and Polygon.

• Book with Authors.

• Lecturer and Students in the classroom.

• Zoo with many creatures, say Dog, Cat, and Bird.

• Channels played on TV.

Zheng-Liang Lu Java Programming 2 23 / 88

Page 25: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

First IS-A Relationship: Class Inheritance

• We can define new classes by inheriting states and behaviorscommonly used in predefined classes (aka prototypes).

• A class is a subclass of some class, which is so-called thesuperclass, by using the extends keyword.

• For example,

1 // superclass2 class A {3 void doAction() {} // A can run doAction().4 }5

6 // subclass7 class B extends A {} // B can also run doAction().

• Note that Java allows single inheritance only.

Zheng-Liang Lu Java Programming 2 24 / 88

Page 26: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Constructor Chaining

• Once the constructor is invoked, JVM will invoke theconstructor of its superclass (recursively).

• You might think that there will be a whole chain ofconstructors called, all the way back to the constructor of theclass Object, the topmost class in Java.

• In this sense, we could say that every class is an immediate ora distant subclass of Object.

Zheng-Liang Lu Java Programming 2 25 / 88

Page 27: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Illustration for Class Hierarchy7

7See Fig. 3-1 in p. 113 of Evans and Flanagan.Zheng-Liang Lu Java Programming 2 26 / 88

Page 28: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

super

• Recall that this is used to refer to the object itself.

• You can use super to refer to (non-private) members of thesuperclass.

• Note that super() can be used to invoke the constructor of itssuperclass, just similar to this().

Zheng-Liang Lu Java Programming 2 27 / 88

Page 29: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Method Overriding

• A subclass is supposed to re-implement the methods inheritedfrom its superclass.

• The requirement of method overriding is as follows:• method signature identical to the one of its superclass;• same return type;• non-reduced visibility relative to the one of its superclass.8

• Note that you cannot override the static methods.

• You should use the annotation9 @Override to help you.

1 class B extends A {2 @Override3 void doAction() { /∗ new impl. w/o changing API ∗/ }4 }

8For example, you cannot reduce the visibility from public to private.9See https://docs.oracle.com/javase/tutorial/java/annotations/.

Zheng-Liang Lu Java Programming 2 28 / 88

Page 30: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example

Zheng-Liang Lu Java Programming 2 29 / 88

Page 31: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Overriding toString()

• The method toString() is invoked by println(), and isinherited from Object.

• By default, it returns the hashcode.10

• It could be overridden so it returns a string of usefulinformation.

1 public class Point {2 ...3 @Override4 public String toString() {5 return "(" + x + "," + y + ")";6 }7 ...8 }

10See https://en.wikipedia.org/wiki/Java_hashCode().Zheng-Liang Lu Java Programming 2 30 / 88

Page 32: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Another Example: ArrayList (Revisited)

1 import java.util.Arrays;2 import java.util.ArrayList;3

4 public class ArrayListDemo2 {5

6 public static void main(String[] args) {7

8 String[] list = {"TW", "US", "JP"};9 ArrayList<String> nations =

10 new ArrayList<>(Arrays.asList(list));11 System.out.println(nations); // output TW, US, JP!12

13 }14

15 }

• Much better!!!

Zheng-Liang Lu Java Programming 2 31 / 88

Page 33: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Subtype Polymorphism11

• The word polymorphism literally means “many forms.”

• Subtype polymorphism allows you to create a single interfaceto different implementations.

• How to make a “single” interface for differentimplementations?

• Use the superclass of those types as the placeholder.• Program to abstraction, not to implementation.

11Also read http://www.javaworld.com/article/3033445/learn-java/

java-101-polymorphism-in-java.html.Zheng-Liang Lu Java Programming 2 32 / 88

Page 34: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Dependency Reduction (Decoupling)

1 class Student {2 void doMyJob() { /∗ Do not know the detail yet. ∗/}3 }4

5 class HighSchoolStudent extends Student {6 void doHomework() {}7 @Override8 void doMyJob() { doHomework(); }9 }

10

11 class CollegeStudent extends Student {12 void writeFinalReports() {}13 @Override14 void doMyJob() { writeFinalReports(); }15 }

Zheng-Liang Lu Java Programming 2 33 / 88

Page 35: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 public class PolymorphismDemo {2

3 public static void main(String[] args) {4 HighSchoolStudent h = new HighSchoolStudent();5 goStudy(h);6 CollegeStudent c = new CollegeStudent();7 goStudy(c);8 }9

10 public static void goStudy(Student s) {11 s.doMyJob();12 }13

14 /∗ no need to write these methods15 public static void goStudy(HighSchoolStudent s) {16 s.doHomework();17 }18

19 public static void goStudy(CollegeStudent s) {20 s.writeFinalReports();21 }22 ∗/23 }

Zheng-Liang Lu Java Programming 2 34 / 88

Page 36: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Why OOP?13

• OOP is the solid foundation of modern (large-scale) softwaredesign.

• In particular, great reuse mechanism and abstraction arerealized by:

• encapsulation isolates the internals (private members) from theexternals, fulfilling the abstraction and providing the sufficientaccessibility (public methods);

• inheritance provides method overriding w/o changing themethod signature;12

• polymorphism exploits the superclass as a placeholder tomanipulate the implementations (subtype objects).

12This leads to the need of “single interface” as mentioned before.13See https://en.wikipedia.org/wiki/Programming_paradigm

Zheng-Liang Lu Java Programming 2 35 / 88

Page 37: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

code reuse

generality

abstraction

variables

generics

application programming

interface (API)inheritance

+ method

overriding +

subtype polymorphism

abstract class & interface as user interface; subclass as

implementationtype parameters

Zheng-Liang Lu Java Programming 2 36 / 88

Page 38: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

• This leads to the production of frameworks14, which actuallydo most of the job, leaving the (application) programmer onlywith the job of customizing with business logic rules andproviding hooks into it.

• This greatly reduces programming time and makes feasible thecreation of larger and larger systems.

• In analog, we often manipulate objects in an abstract level; wedon’t need to know the details when we use them.

• For example, computers, cellphones, driving.

14See https://spring.io/.Zheng-Liang Lu Java Programming 2 37 / 88

Page 39: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Another Example1 class Animal {2 /∗ ignore the previous part ∗/3 void speak() {}4 }5

6 class Dog extends Animal {7 /∗ ignore the previous part ∗/8 @Override9 void speak() { System.out.println("woof"); }

10 }11

12 class Cat extends Animal {13 /∗ ignore the previous part ∗/14 @Override15 void speak() { System.out.println("meow"); }16 }17

18 class Bird extends Animal {19 /∗ ignore the previous part ∗/20 @Override21 void speak() { System.out.println("tweet"); }22 }

Zheng-Liang Lu Java Programming 2 38 / 88

Page 40: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 public class PolymorphismDemo {2

3 public static void main(String[] args) {4

5 Animal[] animals = {new Dog(), new Cat(), new Bird()};6 for (Animal individual: animals)7 individual.speak();8

9 }10

11 }

Zheng-Liang Lu Java Programming 2 39 / 88

Page 41: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Subtype Polymorphism

• For convenience, let U be a subtype of T.

• Liskov Substitution Principle states that T-type objects maybe replaced with U-type objects without altering any of thedesirable properties of T (correctness, task performed,etc.).15,16

• In other words, the references are clients asking the objects(right-hand side) for services!

15Seehttps://en.wikipedia.org/wiki/Liskov_substitution_principle.

16Also seehttps://en.wikipedia.org/wiki/SOLID_(object-oriented_design).

Zheng-Liang Lu Java Programming 2 40 / 88

Page 42: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Casting

• Upcasting (widening conversion) is to cast the Uobject/variable to the T variable.

1 U u1 = new U(); // trivial2 T t1 = u1; // ok3 T t2 = new U(); // ok

• Downcasting (narrow conversion) is to cast the T variable toa U variable.

1 U u2 = (U) t2; // ok, but dangerous. why?2 U u3 = new T(); // error! why?

Zheng-Liang Lu Java Programming 2 41 / 88

Page 43: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Solution: instanceof

• Upcasting is always allowed, but downcasting is not alwaystrue even when you use the cast operator.

• In fact, type checking at compile time is unsound just becausethe cast operator violets the functionality of type checking.

• Moreover, T-type reference can also point to the siblings ofU-type.

• Recall that T-type is used as the placeholder.

• We can use instanceof to check if the referenced object is ofthe target type at runtime.

Zheng-Liang Lu Java Programming 2 42 / 88

Page 44: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example

• The class inheritance can be represented by a digraph(directed graph).

• For example, D is the subtype of A and B, which are bothreachable from D on this digraph.

Zheng-Liang Lu Java Programming 2 43 / 88

Page 45: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 class A {}2 class B extends A {}3 class C extends A {}4 class D extends B {}5 class E extends B {}6 class F extends D {}7

8 public class InstanceofDemo {9

10 public static void main(String[] args) {11

12 Object o = new D();13

14 System.out.println(o instanceof A); // output true15 System.out.println(o instanceof B); // output true16 System.out.println(o instanceof C); // output false17 System.out.println(o instanceof D); // output true18 System.out.println(o instanceof E); // output false19 System.out.println(o instanceof F); // output false20

21 }22 }

Zheng-Liang Lu Java Programming 2 44 / 88

Page 46: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

The Keyword final

• A final variable is a variable which can be initialized once andcannot be changed later.

• The compiler makes sure that you can do it only once.• A final variable is often declared with static keyword and

treated as a constant, for example, Math.PI.

• A final method is a method which cannot be overridden bysubclasses.

• You might wish to make a method final if it has animplementation that should not be changed and it is critical tothe consistent state of the object.

• A class that is declared final cannot be inherited.• For example, again, Math.

Zheng-Liang Lu Java Programming 2 45 / 88

Page 47: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Abstract Classes

• An abstract class is a class declared abstract.

• Typically, abstract classes sit at the top of one class hierarchy,acting as placeholders.

• The abstract classes may have some methods withoutimplementation17 and declared abstract.

• They are abstract methods.• If a class has one or more abstract methods, then the class

itself must be declared abstract.

• All abstract classes cannot be instantiated.

• When inheriting an abstract class, the editor could help yourecall every abstract methods.

17The methods are declared without braces, and followed by a semicolon.Zheng-Liang Lu Java Programming 2 46 / 88

Page 48: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example

• Abstract methods and classes are in italic.

• In this example, the abstract method draw() and resize()should be implemented depending on the real shape.

Zheng-Liang Lu Java Programming 2 47 / 88

Page 49: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Another IS-A Relationship: Interface

• In some situations, objects are supposed to work togetherwithout a proper vertical relationship.

• Consider the class Bird inherited from Animal and Airplaneinherited from Transportation.

• Both Bird and Airplane are able to fly in the sky.• Let’s call the method fly(), for example.

• By semantics, the method fly() could not be defined in theirsuperclasses. (Why?)

• Similar to the case study of Student, we wish those flyableobjects go flying but in one API.

• Using Object as the placeholder? Not really.

• Clearly, we need a horizontal relationship.

Zheng-Liang Lu Java Programming 2 48 / 88

Page 50: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example1 interface Flyable {2 void fly(); // implicitly public and abstract3 }4

5 class Animal {}6

7 class Bird extends Animal implements Flyable {8 void flyByFlappingWings() {9 System.out.println("flapping wings");

10 }11 @Override12 public void fly() { flyByFlappingWings(); }13 }14

15 class Transportation {}16

17 class Airplane extends Transportation implements Flyable {18 void flyByMagic() {19 System.out.println("flying with magicsssss");20 }21 @Override22 public void fly() { flyByMagic(); }23 }

• Again, uniform interface with multiple implementations!Zheng-Liang Lu Java Programming 2 49 / 88

Page 51: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Zheng-Liang Lu Java Programming 2 50 / 88

Page 52: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 public class InterfaceDemo {2

3 public static void main(String[] args) {4

5 Bird b = new Bird();6 goFly(b);7

8 Airplane a = new Airplane();9 goFly(a);

10

11 }12

13 public static void goFly(Flyable f) {14 f.fly();15 }16 }

Zheng-Liang Lu Java Programming 2 51 / 88

Page 53: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Interfaces (1/2)

• An interface is a contract between the object and the client.

• As shown, an interface is a reference type, just like classes.

• Unlike classes, interfaces are used to define methods w/oimplementation so that they cannot be instantiated (directly).

• A class could implements one or multiple interfaces byproviding method bodies for each predefined signature.

Zheng-Liang Lu Java Programming 2 52 / 88

Page 54: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example

Zheng-Liang Lu Java Programming 2 53 / 88

Page 55: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Interfaces (2/2)

• An interface can extend another interfaces.• Like a collection of contracts, in some sense.

• For example, Runnable18 and Serializable19 are two of Javainterfaces.

• In JDK8, we have new features as follows:• we can declare static fields20 and methods in the interfaces;• we can also define default methods in the interfaces;• Java provides so-called functional interfaces for lambdas which

are widely used in the stream framework. (Stay tuned in Java2!)

18See Java Multithread.19Used for an object which can be represented as a sequence of bytes. This

is called object serialization.20But they should be final.

Zheng-Liang Lu Java Programming 2 54 / 88

Page 56: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Timing for Interfaces and Abstract Classes

• Consider using abstract classes if you want to:• share code among several closely related classes• declare non-static or non-final fields

• Consider using interfaces for any of situations as follows:• unrelated classes would implement your interface• specify the behavior of a particular data type, but not

concerned about who implements its behavior• take advantage of multiple inheritance

Zheng-Liang Lu Java Programming 2 55 / 88

Page 57: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Special Issue: Wrapper Classes

Zheng-Liang Lu Java Programming 2 56 / 88

Page 58: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Autoboxing and Unboxing of Primitives

• The Java compiler automatically wraps the primitives in theirwrapper types, and unwraps them where appropriate.

1 ...2 Integer i = 1; // autoboxing3 Integer j = 2;4 Integer k = i + 1; // autounboxing and then autoboxing5

6 System.out.println(k); // output 27 System.out.println(k == j); // output true8

9 Integer m = new Integer(i);10 System.out.println(m == i); // output false?11 System.out.println(m.equals(i)); // output true!?12 ...

Zheng-Liang Lu Java Programming 2 57 / 88

Page 59: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Immutable Objects

• An object is considered immutable if its state cannot changeafter it is constructed.

• Often used for value objects.

• Imagine that there is a pool for immutable objects.

• After the value object is first created, this value object isreused if needed.

• This implies that another object is created when we operateon the immutable object.

• Another example is String objects.

• Good practice when it comes to concurrent programming.21

21See http://www.javapractices.com/topic/TopicAction.do?Id=29.Zheng-Liang Lu Java Programming 2 58 / 88

Page 60: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Zheng-Liang Lu Java Programming 2 59 / 88

Page 61: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 ...2 String str1 = "NTU";3 String str2 = "ntu";4

5 System.out.println("str1 = " + str1.toLowerCase());6 System.out.println("str1 = " + str1);7 str1 = str1.toLowerCase();8 System.out.println("str1 = " + str1);9 System.out.println(str1 == str2); // output false?!

10 System.out.println(str1.intern() == str2); // true!11 ...

Zheng-Liang Lu Java Programming 2 60 / 88

Page 62: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Special Issue: enum Types22

• An enum type is an reference type limited to an explicit set ofvalues.

• An order among these values is defined by their order ofdeclaration.

• There exists a correspondence with string names identical tothe name declared.

22The keyword enum is a shorthand for enumeration.Zheng-Liang Lu Java Programming 2 61 / 88

Page 63: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Colors

1 enum Color {2 RED, GREEN, BLUE; // three options3

4 static Color random() {5 Color[] colors = values();6 return colors[(int) (Math.random() ∗ colors.length)];7 }8 }

• Note that Color is indeed a subclass of enum type with 3static and final references to 3 Color objects corresponding tothe enumerated values.

• This mechanism enhances type safety and makes the sourcecode more readable!

Zheng-Liang Lu Java Programming 2 62 / 88

Page 64: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 class Pen {2 Color color;3 Pen(Color color) { this.color = color; }4 }5

6 class TShirt {7 Color color;8 TShirt(Color color) { this.color = color; }9 void setColor(Color new color) { this.color = new color; }

10 }11

12 public class EnumDemo {13 public static void main(String[] args) {14 Pen crayon = new Pen(Color.RED);15 TShirt t shirt = new TShirt(Color.random());16 System.out.println(crayon.color == T shirt.color);17 }18 }

Zheng-Liang Lu Java Programming 2 63 / 88

Page 65: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Exercise: Directions

1 enum Direction {UP, DOWN, LEFT, RIGHT}2

3 /∗ equivalence4 class Direction {5 final static Direction UP = new Direction("UP");6 final static Direction DOWN = new Direction("DOWN");7 final static Direction LEFT = new Direction("LEFT");8 final static Direction RIGHT = new Direction("RIGHT");9

10 private final String name;11

12 static Direction[] values() {13 return new Direction[] {UP, DOWN, LEFT, RIGHT};14 }15

16 private Direction(String str) {17 this.name = str;18 }19 }20 ∗/

Zheng-Liang Lu Java Programming 2 64 / 88

Page 66: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Package and Access Control

• A package is a grouping of related types providing accessprotection (shown below) and namespace management.

• Type: class, interface, enum, annotation.

Scope \ Modifier private (package) protected public

Within the class X X X XWithin the package x X X XInherited classes x x X XOut of package x x x X

Zheng-Liang Lu Java Programming 2 65 / 88

Page 67: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Special Issue: Nested Classes

• A nested class is a member of its enclosing class.

• Non-static nested classes have access to other members of theenclosing class, even if they are declared private.

• Instead, static nested classes do not have access to otherinstance members of the enclosing class.

• We use nested classes when it needs to:• logically group classes that are only used in one place;• increase encapsulation;• lead to more readable and maintainable code.

• An important use of inner classes is to define an adapter class,acting as a helper object.

Zheng-Liang Lu Java Programming 2 66 / 88

Page 68: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Stack by Linked List

Zheng-Liang Lu Java Programming 2 67 / 88

Page 69: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 public class LinkedListStack {2

3 private Node first;4

5 private class Node {6 int item;7 Node next;8 }9

10 public int pop() {11 int item = first.item;12 first = first.next; // deja vu?13 return item;14 }15

16 public void push(int item) {17 oldfirst = first;18 first = new Node();19 first.item = item;20 first.next = oldfirst;21 }22

23 }

Zheng-Liang Lu Java Programming 2 68 / 88

Page 70: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 public class LinkedListStackDemo {2

3 public static void main(String[] args) {4

5 LinkedListStack stack = new LinkedListStack();6 stack.push(10);7 stack.push(20);8 stack.push(30);9

10 System.out.println(stack.pop()); // output?11 }12

13 }

Zheng-Liang Lu Java Programming 2 69 / 88

Page 71: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Anonymous Class

• Anonymous (inner) classes are an extension of the syntax ofthe new operation, enabling you to declare and instantiate aclass at the same time.

• Use them when you need to use these types only once.

Zheng-Liang Lu Java Programming 2 70 / 88

Page 72: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Button

1 abstract class Button {2 abstract void onClicked();3 }4

5 public class AnonymousClassDemoOne {6

7 public static void main(String[] args) {8

9 Button ok button = new Button() {10 @Override11 public void onClicked() {12 System.out.println("OK");13 }14 };15

16 ok button.onClicked();17 }18 }

Zheng-Liang Lu Java Programming 2 71 / 88

Page 73: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Exercise: Let’s Fly Again

1 interface Flyable {2 void fly();3 }4

5 public class AnonymousClassDemoTwo {6

7 public static void main(String[] args) {8

9 Flyable butterfly = new Flyable() {10 @Override11 public void fly() { /∗ ... ∗/ }12 };13

14 butterfly.fly();15 }16 }

• An interface can be used to instantiate an object indirectly byanonymous classes with implementing the abstract methods.

Zheng-Liang Lu Java Programming 2 72 / 88

Page 74: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Another Example: Iterators

• An iterator is a simple and standard interface to enumerateelements in the data structure.

• In Java, we now proceed to reveal the mechanism of for-eachloops:

• One class implementing the interface Iterable should providethe detail of the method iterator().

• The method iterator() should return an iterator defined by theinterface Iterator, which has two unimplemented methods:hasNext() and next().

• Now your data structure could be compatible with for-eachloops!

Zheng-Liang Lu Java Programming 2 73 / 88

Page 75: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example

1 import java.util.Iterator;2

3 class Box implements Iterable<String> { // <...>: generics4

5 String[] items = {"Java", "C++", "Python"};6

7 public Iterator<String> iterator() {8 return new Iterator<String>() {9 private int ptr = 0;

10

11 public boolean hasNext() {12 return ptr < items.length;13 }14

15 public String next() {16 return items[ptr++];17 }18 };19 }20 }

Zheng-Liang Lu Java Programming 2 74 / 88

Page 76: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 public class IteratorDemo {2 public static void main(String[] args) {3

4 Box books = new Box();5

6 // for−each loop7 /∗8 for (String book: books) {9 System.out.println(book);

10 }11 ∗/12

13 Iterator iterator = books.iterator();14 while (iterator.hasNext())15 System.out.println(iterator.next());16 }17 }

Zheng-Liang Lu Java Programming 2 75 / 88

Page 77: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Static Class

• A static inner class is a nested class declared static.

• Only nested classes can be static.

• Similar to the static members, they can access to other staticmembers without instantiating the outer class.

• In particular, the static nested class can be instantiateddirectly, without instantiating the outer class object first.

• Static nested classes act something like a minipackage.

Zheng-Liang Lu Java Programming 2 76 / 88

Page 78: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example

1 public class StaticClassDemo {2

3 static class Greeting {4

5 @Override6 public String toString() {7 return "This is a static class.";8 }9

10 }11

12 public static void main(String[] args) {13 System.out.println(new StaticClassDemo.Greeting());14 }15

16 }

Zheng-Liang Lu Java Programming 2 77 / 88

Page 79: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Family of Nested Classes

Zheng-Liang Lu Java Programming 2 78 / 88

Page 80: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 class Lecture8 {2

3 "Exceptions and Exception Handling"4

5 }6

7 // keywords:8 assert, try, catch, finally

Zheng-Liang Lu Java Programming 2 79 / 88

Page 81: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Introduction

• Java uses exceptions to handle errors and other exceptionalevents.

• An exception is an event, which occurs during the executionof a program, that disrupts the normal flow of the program’sinstructions.23

• When an error occurs within a method, the method creates anexception object and hands it off to the runtime system.

• Creating an exception object and handing it to the runtimesystem is called throwing an exception.

23Note that the exception should be a force majeure.Zheng-Liang Lu Java Programming 2 80 / 88

Page 82: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

• The runtime system searches the call stack for a method thatcontains a block of code that can handle the exception, calledexception handler

• The exception handler chosen is said to catch the exception.

• Now we proceed to introduce the three components of theexception handler: the try, catch, and finally blocks.

• Java provides the block finally, which always executes whenthe try block exits.

• See the next page.

Zheng-Liang Lu Java Programming 2 81 / 88

Page 83: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 import java.util.InputMismatchException;2 import java.util.Scanner;3

4 public class ExceptionDemo {5

6 public static void main(String[] args) {7

8 Scanner input = new Scanner(System.in);9

10 try {11 System.out.println("Enter an integer?");12 int x = input.nextInt();13 } catch (InputMismatchException e) {14 System.out.println("Not an integer.");15 } catch (Exception e) {16 System.out.println("Unknown exception.");17 } finally {18 System.out.println("Cleanup is done.");19 }20

21 System.out.println("End of program.");22 }23

24 }

Zheng-Liang Lu Java Programming 2 82 / 88

Page 84: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Customized Exception by Class Inheritance

• Java provides us facility to create our own exceptions whichare basically derived classes of Exception.

Zheng-Liang Lu Java Programming 2 83 / 88

Page 85: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Example: Circle1 public class NegativeRadiusException extends

IllegalArgumentException {2

3 public NegativeRadiusException(double r) {4 super("Invalid radius: " + r); // pass the error message5 }6

7 }

1 public class Circle {2

3 private double radius;4

5 public Circle(double r) throws NegativeRadiusException {6 if (r < 0) {7 throw new NegativeRadiusException(r);8 }9 radius = r;

10 }11

12 }

Zheng-Liang Lu Java Programming 2 84 / 88

Page 86: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

1 public class NewExceptionDemo {2

3 public static void main(String[] args) {4

5 new Circle(−10); // check the result!6

7 }8

9 }

Zheng-Liang Lu Java Programming 2 85 / 88

Page 87: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Assertion: Internal Check

• An assertion is a statement that enables you to test yourassumptions about your program.

• Before running the program, add “-ea” to the VM argumentsso that these assertion statements can be tested.

1 public class AssertDemo {2

3 public static void main(String[] args) {4

5 int x = 1;6 assert(x == 2, "x is not equal to 2.");7 // AssertionError occurs!!8 System.out.println("End of program.");9

10 }11

12 }

Zheng-Liang Lu Java Programming 2 86 / 88

Page 88: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Unit Test: JUnit24

• However, we should avoid writing test codes together with thenormal code!

• Try JUnit.

24See https://junit.org/.Zheng-Liang Lu Java Programming 2 87 / 88

Page 89: Java Programming 2 - Object-Oriented Programmingd00922011/java2/java2_oop.pdf · Java Programming 2 Object-Oriented Programming Zheng-Liang Lu Department of Computer Science & Information

Fin.

Zheng-Liang Lu Java Programming 2 88 / 88