• 沒有找到結果。

Java Programming 2

N/A
N/A
Protected

Academic year: 2022

Share "Java Programming 2"

Copied!
93
0
0

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

全文

(1)

Java Programming 2

Zheng-Liang Lu

Department of Computer Science & Information Engineering National Taiwan University

Java2 304 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 / 92

(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.

Plus, we hide internal states and expose methods which perform actions on the aforesaid states.

This is so-callencapsulation, which is one of OO features.1

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

1The rest of features in OO areinheritanceandpolymorphism, which we will see later.

Zheng-Liang Lu Java Programming 2 3 / 92

(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 / 92

(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

As mentioned earlier, these fields are the states of the object.

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 practice, all fields should be declared private to fulfill the concept of encapsulation.

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

What private is good formaintainabilityandmodularity.3

2Thanks to a lively discussion on January 23, 2017.

3Read http://stackoverflow.com/questions/9201603/

are-private-members-really-more-secure-in-java.

Zheng-Liang Lu Java Programming 2 7 / 92

(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 / 92

(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 / 92

(13)

Unified Modeling Language

4

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 / 92

(15)

Constructors

A constructor follows thenew operator.

A constructor acts 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.

Constructors are usedonly during the objection creation.

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 provide specific information to objects by using parameterized constructors.

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 / 92

(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.

You can also use thisto call another constructor in the same classby invokingthis().

(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 / 92

(19)

Instance Members

You may notice that, until now, all members are declared w/o static.

These members are called instance 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 / 92

(21)

Static Members

The static members belong to the class5, and areshared between the instance objects.

These members are ready once the class is loaded.

For example, the main method.

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

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

They are particularly useful for utility methods that perform work that is independent of instances.

For example, factory methods in design patterns.6

5As known as class members.

(22)

Zheng-Liang Lu Java Programming 2 21 / 92

(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 the constructor with no argument

11 // should be placed in the first line

12 this.x = x;

13 this.y = y;

14 }

15 ...

16 }

Zheng-Liang Lu Java Programming 2 23 / 92

(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)

8

Java handles deallocation7 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.

7Release the memory occupied by the unused objects.

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

java/gc01/index.html

Zheng-Liang Lu Java Programming 2 25 / 92

(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 / 92

(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 / 92

(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 public double getLength() {

10 return head.getDistanceFrom(tail);

11 }

12

13 public static double measureLength(Line line) {

14 return line.getLength();

15 }

16 }

(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 / 92

(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 / 92

(35)

Example

1 class Animal {

2 String name;

3 int weight;

4

5 Animal(String s, int w) { name = s; weight = w; }

6

7 void eat() { weight++; }

8 void exercise() { weight−−; }

9 }

10

11 class Human extends Animal {

12 Human(String s, int w) { super(s, w); } // why?

13 void writeCode() {}

14 }

15

16 class Dog extends Animal {

17 Dog(String s, int w) { super(s, w); }

18

19 void watchDoor() {}

20 }

(36)

super

Recall that the keywordthisis used to refer to the object itself.

You can use the keyword superto refer to (non-private) members of the superclass.

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

Zheng-Liang Lu Java Programming 2 35 / 92

(37)

Class Hierarchy

9

(38)

Constructor Chaining

As the constructor is invoked, the constructor of its superclass is invoked accordingly.

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.

So every class is an immediate or a distant subclass of Object.

For example, finalize() and toString() are inherited from Object.

toString(): return a string which can be any information stored in the object.

Zheng-Liang Lu Java Programming 2 37 / 92

(39)

Example

1 class A {

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

3 }

4

5 class B extends A {

6 B() { System.out.println("B is creating..."); }

7

8 @Override // annotation

9 public String toString() { return "say something"; }

10 }

11

12 public class ConstructorChainingDemo {

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

14 B b = new B();

15 System.out.println(b);

16 }

17 }

The println() method (and similar methods) can take an

(40)

Method Overriding

A subclass is allowed to change the behavior inherited from its superclass, if necessary.

If one defines an instance methodwith its signature and return type, all identical to the one defined in its superclass, then we call it method overriding.10

Recall that method overloading occurs only in the same class.

Note that you could invoke the overridden method by using super.

10Notice that the static methods do not follow this rule.

Zheng-Liang Lu Java Programming 2 39 / 92

(41)

Example

(42)

Binding

Association of the method definition to the method call is known as binding.

The binding which can be resolved at the compilation time is known as static binding or early binding.

They are thestatic,privateorfinalmethods.11

If the compiler is not able to resolve the binding, such binding is known as dynamic bindingor late binding.

For example, method overriding.

11We will see thefinalkeyword soon.

Zheng-Liang Lu Java Programming 2 41 / 92

(43)

When there are multiple implementations of the method in the inheritance hierarchy, the one in the “most derived” class (the furthest down the hierarchy) always overrides the others, even if we refer to the object through a reference variable of the superclass type.12

As you can see in Cat Simon.

This is so-called subtype polymorphism.

(44)

Polymorphism

13

The word polymorphismliterally means “many forms.”

Java allows 4 types of polymorphism:

coercion (casting)

ad hoc polymorphism (overloading)

subtype polymorphism

parametric polymorphism (generics)

Modeling polymorphism in a programming language lets you create a uniform interface to different kinds of operands, arguments, and objects.

13Read http://www.javaworld.com/article/3033445/learn-java/

java-101-polymorphism-in-java.html.

Zheng-Liang Lu Java Programming 2 43 / 92

(45)

Example: Uniform Interface

1 class Student {

2 void doMyJob() { /∗ Do not know the detail yet. ∗/}

3 }

4

5 class HighSchoolStudent extends Student {

6 void doHomework() {}

7

8 @Override

9 void doMyJob() { doHomework(); }

10 }

11

12 class CollegeStudent extends Student {

13 void writeFinalReports() {}

14

15 @Override

16 void doMyJob() { writeFinalReports(); }

17 }

(46)

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 // uniform interface, multiple implementations;

11 // enhance the flexibility by reducing dependancy,

12 // for future extension (scalability)

13 public static void goStudy(Student s) {

14 s.doMyJob();

15 }

16

17 /∗ no need to write these methods

18 public static void goStudy(HighSchoolStudent s) {

19 s.doHomework();

20 }

21

22 public static void goStudy(CollegeStudent s) {

23 s.writeFinalReports();

24 }

25 ∗/

26 }

Zheng-Liang Lu Java Programming 2 45 / 92

(47)

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.).14,15

14See

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

(48)

Casting

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

1 T t = new U();

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

1 U u = (U) t; // t is T variable reference to a U object.

Upcasting is always allowed, but downcasting is allowed only when a U object is passed to the U-type variable.

Java type system makes sure that the referenced object provides services adequate for T type.

Zheng-Liang Lu Java Programming 2 47 / 92

(49)

instanceof

However, type-checking in compilation time is unsound.

The operator instanceofchecks if the referenced object is of the type in question.

(50)

Example

1 class T {}

2 class U extends T {}

3

4 public class InstanceofDemo {

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

6 T t1 = new T();

7

8 System.out.println(t1 instanceof U); // output false

9 System.out.println(t1 instanceof T); // output true

10

11 T t2 = new U(); // upcasting

12

13 System.out.println(t2 instanceof U); // output true

14 System.out.println(t2 instanceof T); // output true

15

16 U u = (U) t2; // downcasting; this is ok.

17

18 u = (U) new T(); // pass the compilation; fail during execution!

19 }

20 }

Zheng-Liang Lu Java Programming 2 49 / 92

(51)

Abstraction, Method Overriding, and Polymorphism

JVM invokes the appropriate method for the current object by looking up from the bottom of the class hierarchy to the top.

These methods are also calledvirtual methods.

This preserves the behaviors of the subtype objects and the super-type variables play the role ofplaceholder.

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.

(52)

Exercise

Imagine that we have a zoo with some animals.

1 class Animal {

2 void speak() {}

3 }

4 class Dog extends Animal {

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

6 }

7 class Cat extends Animal {

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

9 }

10 class Bird extends Animal {

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

12 }

13

14 public class PolymorphismDemo {

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

16 Animal[] zoo = {new Dog(), new Cat(), new Bird()};

17 for (Animal a: zoo) a.speak();

18 }

19 }

Zheng-Liang Lu Java Programming 2 51 / 92

(53)

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.

(54)

Abstract Classes

An abstract class is a class declared abstract.

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

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.

16The classes that sit near the bottom of the hierarchy are calledconcrete classes.

Zheng-Liang Lu Java Programming 2 53 / 92

(55)

Example

Abstract methods and classes are in italic.

In this example, the abstract method draw () and resize()

(56)

Another IS-A Relationship

Not all classes share a vertical relationship.

Instead, some are supposed to perform the specific methods without a vertical relationship.

Consider the class Bird inherited from Animal and Airplane inherited from Transportation.

Both Bird and Airplane are able to be in the sky.

So they should perform the method canFly(), for example.

By semantics, the method canFly() could not be defined in their superclasses.

We need ahorizontal relationship.

Zheng-Liang Lu Java Programming 2 55 / 92

(57)

Example

1 interface Flyable {

2 void fly(); // implicitly public, 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

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

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

(58)

Zheng-Liang Lu Java Programming 2 57 / 92

(59)

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 }

(60)

Interfaces

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

For example, the buttons on the television set are the interface between you and the electrical wiring on the other side of its plastic casing.

An interface is also a reference type, just like classes, in which only method signatures are defined.

So they can be the types of reference variables!

Zheng-Liang Lu Java Programming 2 59 / 92

(61)

Note that interfaces cannotbe instantiated (directly).

A class implements one or multipleinterfaces 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 / 92

(63)

Properties of Interfaces

The methods of an interface are implicitlypublic.

In most cases, the class which implements the interface should implement allthe methods defined in the interface.

Otherwise, the class should beabstract.

An interface can extend another interface, just like a class which can extend another class.

In contrast with classes, an interface can extend many interfaces.

(64)

Common interfaces are Runnable17 and Serializable18.

In JDK8, we have new features as follows:

we can declarestaticfields19and 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!)

17See Java Multithread.

18Used for an object which can be represented as a sequence of bytes. This is called object serialization.

19But they should befinal.

Zheng-Liang Lu Java Programming 2 63 / 92

(65)

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

Program to abstraction, not to implementation.20

(66)

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 ...

Zheng-Liang Lu Java Programming 2 65 / 92

(67)
(68)

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 System.out.println(k); // output 2

6

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

8 System.out.println(k.equals(j)); // output true

9 ...

The method equals() inherited from Object is used to compare two objects.

You may override this method if necessary.

Zheng-Liang Lu Java Programming 2 67 / 92

(69)

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.

(70)

Zheng-Liang Lu Java Programming 2 69 / 92

(71)

For example,

1 ...

2 k = new Integer(1);

3 System.out.println(i == k); // output false (why?)

4 System.out.println(k.equals(i)); // output true

5 ...

Good practice when it comes to concurrent programming.21

Another example is String objects.

(72)

enum Types

22

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.

22The keywordenumis a shorthand for enumeration.

Zheng-Liang Lu Java Programming 2 71 / 92

(73)

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!

(74)

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 }

Zheng-Liang Lu Java Programming 2 73 / 92

(75)

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 ∗/

(76)

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.

Zheng-Liang Lu Java Programming 2 75 / 92

(77)

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

(78)

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

Zheng-Liang Lu Java Programming 2 77 / 92

(79)

Family of Nested Classes

(80)

Non-Static Nested Classes

Depending on how and where you define them, they can be further divided in three types:

inner classes

method-local inner classes

anonymous inner 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.

For static members in the inner classes,

you can declare a static variable which is supposed to befinal;

however, static methods can only be declared in a static or top level type.

Zheng-Liang Lu Java Programming 2 79 / 92

(81)

Example: Inner Class

1 class OuterClass {

2 private int x = 1;

3 InnerClass innerObject = new InnerClass();

4

5 class InnerClass {

6 public void print() {

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

8 }

9 }

10 }

11

12 public class InnerClassDemo {

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

14 OuterClass outerObject = new OuterClass();

15 outerObject.innerObject.print(); // output 1

16

17 // you cannot do below

18 InnerClass innerObject = new InnerClass();

19 }

20 }

(82)

Example: Method-Local Inner Class

1 class OuterClass {

2 private int x = 1;

3

4 void doSomething() {

5 class LocalClass { // should be in the beginning

6 int y = 2;

7 static int z = 3; // implicitly final

8

9 void print() {

10 System.out.println(x);

11 System.out.println(y);

12 System.out.println(z);

13 }

14 }

15

16 LocalClass w = new LocalClass();

17 w.print();

18 }

19 }

20

21 public class InnerClassDemo {

22 ...

23 }

Zheng-Liang Lu Java Programming 2 81 / 92

(83)

Anonymous Inner Class

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

However, these do not have a name.

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

(84)

Example

1 abstract class A {

2 abstract void foo();

3 }

4

5 public class AnonymousClassDemoOne {

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

7 A a = new A() {

8 public void foo() { /∗ different implementation ∗/ }

9 void helper() { /∗ a subroutine for foo ∗/ }

10 };

11

12 a.foo();

13 }

14 }

You may invoke a.foo() but not a.helper() because helper() is not defined in class A.

Zheng-Liang Lu Java Programming 2 83 / 92

(85)

Exercise

1 interface B {

2 void foo();

3 }

4

5 public class AnonymousClassDemoTwo {

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

7 B b = new B() {

8 public void foo() { /∗ different implementation ∗/ }

9 };

10

11 b.foo();

12 }

13 }

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

(86)

One of Adapters: 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().

Zheng-Liang Lu Java Programming 2 85 / 92

(87)

Example

1 import java.util.Iterator;

2

3 class Box implements Iterable<Integer> { // <...> is generic

4

5 int[] items = {10, 20, 30};

6

7 public Iterator<Integer> iterator() {

8 return new Iterator<Integer>() {

9 private int ptr = 0;

10

11 public boolean hasNext() {

12 return ptr< items.length;

13 }

14

15 public Integer next() {

16 return items[ptr++];

17 }

18 };

19 }

20 }

參考文獻

相關文件

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