• 沒有找到結果。

Java Programming 2

N/A
N/A
Protected

Academic year: 2022

Share "Java Programming 2"

Copied!
92
0
0

加載中.... (立即查看全文)

全文

(1)

Java Programming 2

Zheng-Liang Lu

Department of Computer Science & Information Engineering National Taiwan University

Java2 306 Fall 2018

(2)

1 class Lecture7 {

2

3 // Object−Oriented Programming

4 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 / 91

(3)

Observation in Real World

Look around.

We can easily find many examples for real-world objects.

For example, a person with a bottle of water.

Real-world objects all have states andbehaviors.

What states can the object need?

What behaviors can the object perform on the states?

Identifying these states and behaviors for real-world objects is a great way to begin thinking inobject-oriented programming.

From now, OO is a shorthand for “object-oriented.”

(4)

Objects

An object keeps its states in fields(or attributes) and exposes its behaviors throughmethods.

For example, describe your cellphone.

Attributes: battery status, 4G signal strength, contact info in your phonebook, photos in albums, musics, clips, and so on.

Functions?

Before creating the objects, we need to define a new class as their prototype (or concept).

Zheng-Liang Lu Java Programming 2 3 / 91

(5)

Classes

We often find many objects all of the same kind.

For example, Student A and Student B are two instances of

“Student”.

Every student needs a name and a student ID.

Every student should do homework and pass the final exams.

A class is the blueprint to create class instances which are runtime objects.

In the other word, an object is an instance of some associated class.

In Java, classes are the building blocks in every program.

Once the class is defined, we can use this class to create objects.

(6)

Example: Points in 2D Coordinate

1 public class Point {

2 // data members: so−called fields or attributes

3 double x, y;

4 }

1 public class PointDemo {

2 public static void main(String[] args) {

3 // now create a new instance of Point

4 Point p1 = new Point();

5 p1.x = 1;

6 p1.y = 2;

7 System.out.printf("(%d, %d)\n", p1.x, p1.y);

8

9 // create another instance of Point

10 Point p2 = new Point();

11 p2.x = 3;

12 p2.y = 4;

13 System.out.printf("(%d, %d)\n", p2.x, p2.y);

14 }

15 }

Zheng-Liang Lu Java Programming 2 5 / 91

(7)

Class Definition

First, give a class name with the first letter capitalized, by convention.

The class body, surrounded by balanced curly braces {}, contains data members (fields) and function members (methods).

(8)

Data Members

Each field may have an access modifier, say public and private.

public: accessible by all classes

private: accessible only within its own class

We can decide if these fields are accessible!

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

So all fields should be declaredprivate.

This is so-calledencapsulation.

However, this private modifier does not quarantine any security.1

What private is good formaintainabilityandmodularity.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 7 / 91

(9)

Function Members

As said, the fields are hidden.

So we provide getters andsetters if necessary:

getters: return some 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.

(10)

Example: Point (Encapsulated)

1 public class Point {

2 // data members: fields or attributes

3 private double x;

4 private double y;

5

6 // function members: methods

7 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 9 / 91

(11)

Exercise: Phonebook

1 public class Contact {

2 private String name;

3 private String phoneNumber;

4

5 public String getName() { return name; }

6 public String getPhoneNumber() { return phoneNumber; }

7

8 public void setName(String new name) { name = new name; }

9 public void setPhoneNumber(String new phnNum) {

10 phoneNumber = new phnNum;

11 }

12 }

(12)

1 public class PhonebookDemo {

2

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

4 Contact c1 = new Contact();

5 c1.setName("Arthur");

6 c1.setPhoneNumber("09xxnnnnnn");

7

8 Contact c2 = new Contact();

9 c1.setName("Emma");

10 c1.setPhoneNumber("09xxnnnnnn");

11

12 Contact[] phonebook = {c1, c2};

13

14 for (Contact c: phonebook) {

15 System.out.printf("%s: %s\n", c.getName(),

16 c.getPhoneNumber());

17 }

18 }

19 20 }

Zheng-Liang Lu Java Programming 2 11 / 91

(13)

Unified Modeling Language

3

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

Free software:

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

(14)

Example: Class Diagram for Point

Modifiers can be placed before both fields and methods:

+ forpublic

− forprivate

Zheng-Liang Lu Java Programming 2 13 / 91

(15)

Constructors

A constructor follows thenew operator, acting like other methods.

However, its names should be identical to the name of the classand 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 a default constructor for you.

Moreover, adding any explicit constructor disables the default constructor.

(16)

Parameterized Constructors

You can initialize an object once the object is created.

For example,

1 public class Point {

2 ...

3 // default constructor

4 public Point() {

5 // do something in common

6 }

7

8 // parameterized constructor

9 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 15 / 91

(17)

Self Reference

You can refer to any (instance) member of the currentobject within methods and constructors by usingthis.

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

Recall the variable scope.

You can also use thisto call another constructor in the same class, say this().

(18)

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 thisoperator cannot be used in staticmethods.

Zheng-Liang Lu Java Programming 2 17 / 91

(19)

Instance Members

Since this lecture, all members are declared w/o static, so-calledinstance members.

These instance members are available only after the object is created.

This implies that each object has its own states and does some actions.

(20)

Zheng-Liang Lu Java Programming 2 19 / 91

(21)

Static Members

Static members belong to the class4, and areshared between the instance objects.

Those are ready once the class is loaded.

For example, the main methods.

They can be invoked directly by the class name without any instance.

For example, Math.random() and Math.PI.

Particularly useful for utility methods that perform work which is independent of instances.

For example, factory methods in design patterns.5

4Aka class members.

(22)

Zheng-Liang Lu Java Programming 2 21 / 91

(23)

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

However, static methods cannot access to instance members directly. (Why?)

For example,

1 ...

2 public double getDistanceFrom(Point that) {

3 return Math.sqrt(Math.pow(this.x − that.x, 2)

4 + Math.pow(this.y − that.y, 2));

5 }

6

7 public static double measure(Point first, Point second) {

8 // You cannot use this.x and this.y here!

9 return Math.sqrt(Math.pow(first.x− second.x, 2)

10 + Math.pow(first.y − second.y, 2));

11 }

12 ...

(24)

Example: Count of Points

1 public class Point {

2 ...

3 private static int numOfPoints = 0;

4

5 public Point() {

6 numOfPoints++;

7 }

8

9 public Point(int x, int y) {

10 this(); // calling Line 5

11 this.x = x;

12 this.y = y;

13 }

14 ...

15 }

Note that invoking constructors (like Line 10) should be placed in the first statement in one constructor.

Zheng-Liang Lu Java Programming 2 23 / 91

(25)

Exercise: Singleton

In some situations, you may create theonly instance of the class.

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 }

(26)

Garbage Collection (GC)

7

Java handles deallocation6 automatically.

Timing: preset period or when memory stress occurs.

GC is the process of looking at theheap, identifying if the objects are in use, and deleting those unreferenced objects.

An object is unreferencedif the object is no longer referenced by any part of your program. (How?)

Simply assignnullto the reference to make the object unreferenced.

Note that you may invoke System.gc() to execute the deallocation procedure.

However, frequent invocation of GC is time-consuming.

6Release the memory occupied by the unused objects.

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

java/gc01/index.html

Zheng-Liang Lu Java Programming 2 25 / 91

(27)

finalize()

The method finalize() conducts a specific task that will be executed right before the object is reclaimed by GC.

For example, closing files and terminating network connections.

The finalize() method can beonly invoked prior to GC.

In practice, it must not rely on the finalize() method for normal operations. (Why?)

(28)

Example

1 public class Garbage {

2 private static int numOfObjKilled = 0;

3

4 public void finalize() {

5 numOfObjKilled++;

6 }

7

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

9 double n = 1e7;

10 for (int i = 1; i <= n; i++)

11 new Garbage(); // lots of unreferenced objects

12 System.out.println(numOfObjKilled);

13 }

14 }

You may try different number for instance creation.

The number of the objects reclaimed by GC is uncertain.

Zheng-Liang Lu Java Programming 2 27 / 91

(29)

HAS-A Relationship

Associationis a weak relationship where all objects have their own lifetime and there is no ownership.

For example, teacher ↔ student; doctor ↔ patient.

If A uses B, then it is anaggregation, stating that B exists independently from A.

For example, knight ↔ sword; company ↔ employee.

If A owns B, then it is acomposition, meaning that B has no meaning or purpose in the system without A.

For example, house ↔ room.

(30)

Example: Lines

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

Zheng-Liang Lu Java Programming 2 29 / 91

(31)

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 public static double measure(Line line) {

16 return line.getLength();

17 }

18 }

(32)

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.

More.

Zheng-Liang Lu Java Programming 2 31 / 91

(33)

More About Objects

Inheritance: passing down states and behaviors from the parents to their children.

Interfaces: requiring objects for the demanding methods which are exposed to the outside world.

Polymorphism

Packages: grouping related types, and providing access controls and name space management.

Immutability

Enumeration types

Inner classes

(34)

First IS-A Relationship: Inheritance

The relationships among Java classes formclass hierarchy.

We can define new classes by inheritingcommonly used states and behaviors from predefined classes.

A class is a subclassof some class, which is so-called the superclass, by using the extends keyword.

For example, BextendsA.

In semantics, Bis a special case of A, or we could say B specializes A.

For example, human and dog are two specific types of animals.

When both B and C are subclasses of A, we say that A generalizes B and C. (D´ej`a vu.)

Note that Java allows single inheritanceonly.

Zheng-Liang Lu Java Programming 2 33 / 91

(35)

Example

1 class Animal {

2 int weight;

3 void eat() { weight++; }

4 void exercise() { weight−−; }

5 }

6

7 class Human extends Animal {

8 void writeCode() {}

9 }

10

11 class Dog extends Animal {

12 void watchDoor() {}

13 }

How could Human and Dog possess those members of Animal?

In this way, it is convenient to define, say Cat, by extending

(36)

Constructor Chaining

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

You might think that there will be a whole chain of

constructors called, all the way back to the constructor of the class Object, the topmost class in Java.

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

Zheng-Liang Lu Java Programming 2 35 / 91

(37)

Illustration for Class Hierarchy

8

(38)

Example: An Evidence

1 class A {

2 A() { System.out.println("A is creating..."); }

3 }

4

5 class B extends A {

6 B() {

7 super(); // you don’t need to do this unless necessary.

8 System.out.println("B is creating...");

9 }

10 }

11

12 public class ConstructorChainingDemo {

13 public static void main(String[] args) {

14 B b = new B();

15 }

16 }

Zheng-Liang Lu Java Programming 2 37 / 91

(39)

super

Recall that thisis used to refer to the object itself.

You can usesuper to refer to (non-private) members of the superclass.

Note thatsuper() can be used to invoke the constructor of its superclass, just similar to this().

(40)

Method Overriding (1/2)

A subclass is supposed tore-implement the methods inherited from its superclass.

Can you smell it?

For example, toString() is inherited from Object.

This method will be invoked by println().

It returns the hashcode9of the object by default.

It could beoverriddenso it returns a string of desirable information.

Another example we have encountered is finalize().

9See https://en.wikipedia.org/wiki/Java_hashCode().

Zheng-Liang Lu Java Programming 2 39 / 91

(41)

Example

(42)

Method Overriding (2/2)

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.

Note that you cannot override the static methods.

You could invoke the overridden method by using super.

You should use the annotation10 @Overrideto help you.

1 class Cat extends Animal {

2 @Override

3 void eat() { weight += 2; }

4 5 }

10See https://docs.oracle.com/javase/tutorial/java/annotations/.

Zheng-Liang Lu Java Programming 2 41 / 91

(43)

Polymorphism

12

The word polymorphismliterally means “many forms.”

Java allows 4 types of polymorphism:

coercion (casting)

ad hoc polymorphism (overloading)

subtype polymorphism

parametric polymorphism (generics)11

Subtype polymorphism allows you to create asingle interface to different types (implementations).

How to make a “single” interface for different types?

Use thesuperclass of those types as theplaceholder.

Program to abstraction, not to implementation.

11We will introduce Java generics in Java Programming 2. Stay tuned.

(44)

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 @Override

8 void doMyJob() { doHomework(); }

9 }

10

11 class CollegeStudent extends Student {

12 void writeFinalReports() {}

13 @Override

14 void doMyJob() { writeFinalReports(); }

15 }

Zheng-Liang Lu Java Programming 2 43 / 91

(45)

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 methods

15 public static void goStudy(HighSchoolStudent s) {

16 s.doHomework();

17 }

18

19 public static void goStudy(CollegeStudent s) {

20 s.writeFinalReports();

21 }

22 ∗/

}

(46)

Why OOP?

First, you may know that there are many programming paradigms.13

OOP is the solid foundation of modern software design.

In particular, encapsulation, inheritance, and polymorphism provide a greatreuse mechanism and a greatabstraction.

Encapsulationisolates the internals (private members) from the externals, fulfilling the abstraction and providing the sufficient accessibility (public methods).

Inheritanceprovides method overriding w/o changing the method signature.14

Polymorphismexploits the superclass as a placeholder to manipulate the implementations (sub-type objects).

13See https://en.wikipedia.org/wiki/Programming_paradigm.

14This leads to the need of “single interface” as mentioned before.

Zheng-Liang Lu Java Programming 2 45 / 91

(47)

This leads to the production offrameworks15, which actually do most of the job, leaving the (application) programmer only with the job of customizing withbusiness logic rules and providing hooks into it.

This greatly reduces programming time and makes feasible the creation of larger and larger systems.

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

For example, computers, cellphones, driving.

(48)

Another Example

1 class Animal {

2 /∗ ignore the previous part ∗/

3 void speak() {}

4 }

5

6 class Dog extends Animal {

7 /∗ ignore the previous part ∗/

8 @Override

9 void speak() { System.out.println("woof"); }

10 }

11

12 class Cat extends Animal {

13 /∗ ignore the previous part ∗/

14 @Override

15 void speak() { System.out.println("meow"); }

16 }

17

18 class Bird extends Animal {

19 /∗ ignore the previous part ∗/

20 @Override

21 void speak() { System.out.println("tweet"); }

22 }

Zheng-Liang Lu Java Programming 2 47 / 91

(49)

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 each: animals)

7 each.speak();

8

9 }

10 11 }

(50)

Subtype Polymorphism

For convenience, let U be a subtype of T.

Liskov Substitution Principle states that T-type objects may be replaced with U-type objects without altering any of the desirable properties of T (correctness, task performed, etc.).16,17

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

16See

https://en.wikipedia.org/wiki/Liskov_substitution_principle.

17Also see

https://en.wikipedia.org/wiki/SOLID_(object-oriented_design).

Zheng-Liang Lu Java Programming 2 49 / 91

(51)

Casting

Upcasting (widening conversion) is to cast the U object/variable to the T variable.

1 U u1 = new U(); // trivial

2 T t1 = u1; // ok

3 T t2 = new U(); // ok

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

1 U u2 = (U) t2; // ok, but dangerous. why?

2 U u3 = new T(); // error! why?

(52)

Solution: instanceof

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

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

Moreover, T-type reference can also point to the siblings of U-type.

Recall that T-type is used as the placeholder.

We can useinstanceof to check if the referenced object is of the target type at runtime.

Zheng-Liang Lu Java Programming 2 51 / 91

(53)

Example

1 class T {}

2 class U extends T {}

3 class W extends T {}

4

5 public class InstanceofDemo {

6

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

8

9 T t = new U();

10

11 System.out.println(t instanceof T); // output true

12 System.out.println(t instanceof U); // output true

13 System.out.println(t instanceof W); // output false

14

15 W w = new W();

16

17 System.out.println(w instanceof T); // output true

18 System.out.println(w instanceof U); // output false

19 System.out.println(w instanceof W); // output true

20

21 }

(54)

final

A finalvariable is a variable which can be initialized once and cannot be changed later.

The compiler makes sure that you can do itonly once.

Afinalvariable is often declared with statickeyword and treated as a constant, for example, Math.PI.

A finalmethod is a method whichcannot be overridden by subclasses.

You might wish to make a methodfinalif it has an

implementation that should not be changed and it is critical to the consistent state of the object.

A class that is declared finalcannot be inherited.

For example, again, Math.

Zheng-Liang Lu Java Programming 2 53 / 91

(55)

Abstract Classes

An abstract class is a class declared abstract.

The classes that sit at the top of an object hierarchy are typically abstractclasses.18

These abstract class may or may not haveabstract methods, which are methods declaredwithout implementation.

More explicitly, the methods are declared without braces, and followed by a semicolon.

If a class has one or moreabstractmethods, then the class itself must be declaredabstract.

Allabstract classes cannot be instantiated.

Moreover, abstractclasses act as placeholders for the subclass objects.

(56)

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 55 / 91

(57)

Another IS-A Relationship

In some situations, objects are supposed to work together without a vertical relationship.

Consider the class Bird inherited from Animal and Airplane inherited 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 their superclasses. (Why?)

Similar to the case study of Student, we wish those flyable objects go flying but in a single interface.

Using Object as the placeholder?

Clearly, we need a horizontalrelationship.

(58)

Example

1 interface Flyable {

2 void fly(); // implicitly public and abstract

3 }

4

5 class Animal {}

6

7 class Bird extends Animal implements Flyable {

8 void flyByFlappingWings() {

9 System.out.println("flapping wings");

10 }

11 @Override

12 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 @Override

22 public void fly() { flyByMagic(); }

23 }

Again, uniform interface with multiple implementations!

Zheng-Liang Lu Java Programming 2 57 / 91

(59)
(60)

1 public class InterfaceDemo {

2 public static void main(String[] args) {

3 Bird b = new Bird();

4 goFly(b);

5

6 Airplane a = new Airplane();

7 goFly(a);

8 }

9

10 public static void goFly(Flyable f) {

11 f.fly();

12 }

13 }

Zheng-Liang Lu Java Programming 2 59 / 91

(61)

Interfaces (1/2)

An interface forms acontract between the object and the outside world.

For example, the buttons on remote controls for some machine.

As you can see, an interface is a reference type, just like classes

Unlike classes, interfaces are used to define methods w/o implementation so that theycannot be instantiated (directly).

A class could implementsone or multiple interfaces by providing method bodies for each predefined signature.

Thisrequires an object providing a different set of services.

For example, combatants in RPG can also buy and sell stuffs in the market.

(62)

Example

Zheng-Liang Lu Java Programming 2 61 / 91

(63)

Interfaces (2/2)

An interface can extend another interfaces.

Like a collection of contracts, in some sense.

For example, Runnable19and Serializable20 are two of Java interfaces.

In JDK8, we have new features as follows:

we can declarestaticfields21and methods in the interfaces;

we can also definedefaultmethods in the interfaces;

Java provides so-calledfunctional interfacesforlambdas which are widely used inthe stream framework. (Stay tuned in Java 2!)

19See Java Multithread.

20Used for an object which can be represented as a sequence of bytes. This

(64)

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 63 / 91

(65)

Special Issue: Wrapper Classes

To treat values as objects, Java supplies standard wrapper classes for each primitive type.

For example, you can construct a wrapper object from a primitive value or from a string representation of the value.

1 ...

2 Double pi = new Double("3.14");

3 ...

(66)

Zheng-Liang Lu Java Programming 2 65 / 91

(67)

Autoboxing and Unboxing of Primitives

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

1 ...

2 Integer i = 1; // autoboxing

3 Integer j = 2;

4 Integer k = i + 1; // autounboxing and then autoboxing

5

6 System.out.println(k); // output 2

7 System.out.println(k == j); // output true

8

9 Integer m = new Integer(i);

10 System.out.println(m == i); // output false?

11 System.out.println(m.equals(i)); // output true!?

12 ...

(68)

Immutable Objects

An object is considered immutableif its state cannot change after 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 is reused if needed.

This implies that another object is created when we operate on the immutable object.

Another example is String objects.

Good practice when it comes to concurrent programming.22

22See http://www.javapractices.com/topic/TopicAction.do?Id=29.

Zheng-Liang Lu Java Programming 2 67 / 91

(69)
(70)

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); // output true

11 ...

Zheng-Liang Lu Java Programming 2 69 / 91

(71)

Special Issue: enum Types

23

An enum type is an reference type limited to an explicit set of values.

An order among these values is defined by their order of declaration.

There exists a correspondence with string names identical to the name declared.

(72)

Example: Colors

1 enum Color {

2 RED, GREEN, BLUE; // three options

3

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 enumtype with 3 static andfinal references to 3 Color objects corresponding to the enumerated values.

This mechanism enhances type safety and makes the source code more readable!

Zheng-Liang Lu Java Programming 2 71 / 91

(73)

1 Class Pen {

2 Color color;

3 Pen(Color color) { this.color = color; }

4 }

5

6 Class Clothes {

7 Color color;

8 T Shirt(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 Clothes T shirt = new Clothes(Color.random());

16 System.out.println(crayon.color == T shirt.color);

17 }

18 }

(74)

Exercise: Directions

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

2

3 /∗ equivalence

4 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 73 / 91

(75)

Special Issue: Packages

We organize related types into packages for the following purposes:

To make types easier to find and use

To avoid naming conflicts

To control access

For example, fundamental classes are in java.lang and classes for I/O are in java.io.

(76)

Access Control

Scope \ Modifier private (package) protected public

Within the class X X X X

Within the package x X X X

Inherited classes x x X X

Out of package x x x X

Zheng-Liang Lu Java Programming 2 75 / 91

(77)

Special Issue: Nested Classes

A nested class is a member of its enclosing class.

Non-staticnested classes have access to other members of the enclosing class, even if they are declared private.

Instead, static nested classes do not have access to other instance 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

(78)

Family of Nested Classes

Zheng-Liang Lu Java Programming 2 77 / 91

(79)

Non-Static Nested Classes

Unlike a normal class, an inner class can be declared private.

Note that the creation of inner-type objects is available after the outer-type object is created.

In other words, you cannot invoke the constructor of the inner type without having the outer type object.

In the inner classes, you can declare finalstatic variables but no static methods.

(80)

Example: Inner Class

1 class OuterClass {

2

3 private int x = 1;

4 private InnerClass innerObject = new InnerClass();

5

6 class InnerClass {

7 public void print() {

8 System.out.println(x); // ok!

9 }

10 }

11

12 void doSomeAction() { innerObject.print(); }

13 }

14

15 public class InnerClassDemo {

16 public static void main(String[] args) {

17 new OuterClass().doSomeAction(); // output 1

18

19 new InnerClass(); // you cannot do this

20 }

21 }

Zheng-Liang Lu Java Programming 2 79 / 91

(81)

Example: Method-Local Inner Class

1 class OuterClass {

2

3 void doSomething() {

4 class LocalClass { // should be in the beginning

5 private int x = 2;

6 void print() { System.out.println(x); }

7 }

8

9 new LocalClass().print(); // output 1 and 2

10 }

11 }

(82)

Anonymous Class

Anonymous (inner) classes are an extension of the syntax of thenew operation, enabling you to declare and instantiate a class at the same time.

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

Zheng-Liang Lu Java Programming 2 81 / 91

(83)

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 @Override

11 public void onClicked() {

12 System.out.println("OK");

13 }

14 };

15

16 ok button.onClicked();

17 }

18 }

(84)

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 @Override

11 public void fly() { /∗ ... ∗/ }

12 };

13

14 butterfly.fly();

15 }

16 }

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

Zheng-Liang Lu Java Programming 2 83 / 91

(85)

Another Example: Iterators

An important use of inner classes is to define anadapter class as a helper object.

Using adapter classes, we can write classes more naturally, without having to anticipate every conceivable user’s needs in advance.

Instead, you provide adapter classes that marry your class to a particular interface.

For example, an iteratoris a simple and standard interface to enumerate elements in data structures.

The class which implements the interface Iterable has the responsibility to provide an iterator.

An iterator is defined in the interface Iterator with two uninplemented methods: hasNext() and next().

參考文獻

相關文件

In this paper, we extend this class of merit functions to the second-order cone complementarity problem (SOCCP) and show analogous properties as in NCP and SDCP cases.. In addition,

• Uses a nested structure to accumulate path data as the simulation is running. • Uses a multiple branch structure to choose the

/** Class invariant: A Person always has a date of birth, and if the Person has a date of death, then the date of death is equal to or later than the date of birth. To be

• Instead, static nested classes do not have access to other instance members of the enclosing class. • We use nested classes when it

• Non-static nested classes, aka inner classes, have access to other members of the enclosing class, even if they are declared private. • Instead, static nested classes do not

Our main goal is to give a much simpler and completely self-contained proof of the decidability of satisfiability of the two-variable logic over data words.. We do it for the case

OpenGL 4.2 Reference card: Blue means!. deprecated

If we would like to use both training and validation data to predict the unknown scores, we can record the number of iterations in Algorithm 2 when using the training/validation