51
Java Loose Ends 27 December 2019 OSU CSE 1

Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Java Loose Ends

27 December 2019 OSU CSE 1

Page 2: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

What Else?

• A few Java issues introduced earlier deserve a more in-depth treatment:– Try-Catch and Exceptions– Members (static vs. instance)– Nested interfaces and classes– Access modifiers– “Final”

27 December 2019 OSU CSE 2

Page 3: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Exceptions• An exception indicates a problem with an

application that entails (in Java) a dramatic change of control flow

• Vocabulary: Exceptions (and Errors) are– “thrown” by a component implementation– “caught” by a client

27 December 2019 OSU CSE 3

Page 4: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Syntax of Try-Catch• In a client, a try-catch statement is used to

catch exceptions:

try {statements

} catch(exceptionType1 identifier1) {handler for type1

} catch(exceptionType2 identifier2) {handler for type2

}. . .

27 December 2019 OSU CSE 4

Page 5: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Execution of Try-Catch• If nothing is thrown during execution of the

statements in the try block:– The try block finishes successfully– All catch clauses are ignored (skipped)– Execution continues after the try-catch

27 December 2019 OSU CSE 5

Page 6: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Catching an Exception• If something is thrown during execution of the

statements in the try block:1. The rest of the code in the try block is skipped2. The catch clauses are examined top to bottom for the

first matching catch3. If an appropriate catch clause is found:

The body of the catch clause is executed The remaining catch clauses are skipped

4. If no such catch clause is found: The exception is thrown to the outer block, which is either

– A try block (that potentially handles it, in the same manner)– A method body (resulting in it being thrown to its client)

27 December 2019 OSU CSE 6

Page 7: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Use Exceptions in Your Design?

• Best practice suggests exceptions should be reserved for unexpected situations:– Problems external to the application– Resource exhaustion– Problems that cannot be handled with

checkable preconditions in contracts

27 December 2019 OSU CSE 7

Page 8: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Use Exceptions in Your Design?

• Best practice suggests exceptions should be reserved for unexpected situations:– Problems external to the application– Resource exhaustion– Problems that cannot be handled with

checkable preconditions in contracts

27 December 2019 OSU CSE 8

Example: there is a hardware problem with a

disk drive.

Page 9: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Use Exceptions in Your Design?

• Best practice suggests exceptions should be reserved for unexpected situations:– Problems external to the application– Resource exhaustion– Problems that cannot be handled with

checkable preconditions in contracts

27 December 2019 OSU CSE 9

Example: the JVM is out of memory for this

application.

Page 10: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Use Exceptions in Your Design?

• Best practice suggests exceptions should be reserved for unexpected situations:– Problems external to the application– Resource exhaustion– Problems that cannot be handled with

checkable preconditions in contracts

27 December 2019 OSU CSE 10

Example: a file does not exist—because it has been deleted after its existence has already

been “confirmed”.

Page 11: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Hierarchy of Classes

27 December 2019 OSU CSE 11

Error Exception

Throwable

Page 12: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Hierarchy of Classes

27 December 2019 OSU CSE 12

Error Exception

Throwable

“Unrecoverable”: hardware, JVM, or application error

(e.g., “out of memory”)

“Recoverable”:application problem

(e.g., “file not found”)

Page 13: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Hierarchy of Error Classes

27 December 2019 OSU CSE 13

Error Exception

Throwable

AssertionErrorVirtualMachine-Error

OutOfMemory-Error

Page 14: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Hierarchy of Error Classes

27 December 2019 OSU CSE 14

Error Exception

Throwable

AssertionErrorVirtualMachine-Error

OutOfMemory-Error

This is thrown by an assert statement when the condition is false: something is wrong with

your program.

Page 15: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Hierarchy of Error Classes

27 December 2019 OSU CSE 15

Error Exception

Throwable

AssertionErrorVirtualMachine-Error

OutOfMemory-Error There are many more

subclasses of Error!

Page 16: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Hierarchy of Exception Classes

27 December 2019 OSU CSE 16

Error Exception

Throwable

AssertionErrorVirtualMachine-Error

OutOfMemory-Error

Runtime-Exception IOException

IndexOutOf-BoundsException

NullPointer-Exception

Arithmetic-Exception

Page 17: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Hierarchy of Exception Classes

27 December 2019 OSU CSE 17

Error Exception

Throwable

AssertionErrorVirtualMachine-Error

OutOfMemory-Error

Runtime-Exception IOException

IndexOutOf-BoundsException

NullPointer-Exception

Arithmetic-Exception

There are many more subclasses of Exception, RuntimeException, and

IOException!

Page 18: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Hierarchy of Exception Classes

27 December 2019 OSU CSE 18

Error Exception

Throwable

AssertionErrorVirtualMachine-Error

OutOfMemory-Error

Runtime-Exception IOException

IndexOutOf-BoundsException

NullPointer-Exception

Arithmetic-Exception

With RuntimeExceptionand its subclasses,

something is wrong with your program.

Page 19: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Unchecked vs. Checked• Unchecked exceptions are:

– Error and its subclasses– RuntimeException and its subclasses

• The rest are checked exceptions– “Checked” means that the compiler checks

that a method whose body contains a statement that might throw the exception either catches it, or explicitly “propagates it up the call chain” by declaring that it also throws the exception

27 December 2019 OSU CSE 19

Page 20: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Unchecked vs. Checked

27 December 2019 OSU CSE 20

Exception

Throwable

Runtime-Exception IOException

IndexOutOf-BoundsException

NullPointer-Exception

Arithmetic-Exception

Error

AssertionErrorVirtualMachine-Error

OutOfMemory-Error

Page 21: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Members

• A class may have different kinds of members:– Variables/fields/data members– Constructors– Methods– Nested classes

• All except constructors may be either static members or instance members

27 December 2019 OSU CSE 21

Page 22: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Members

• A class may have different kinds of members:– Variables/fields/data members– Constructors– Methods– Nested classes

• All except constructors may be either static members or instance members

27 December 2019 OSU CSE 22

Static methods and instance methods have already been

discussed...

Page 23: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Members

• A class may have different kinds of members:– Variables/fields/data members– Constructors– Methods– Nested classes

• All except constructors may be either static members or instance members

27 December 2019 OSU CSE 23

Static members of a class are also called class members, for

reasons that will presently become clear.

Page 24: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Static vs. Instance Variables

• At run-time, a Java program has separate representations for:– All static variables for each class C

– All instance variables for each instance of C, i.e., for each object with dynamic type C

• Bytecode for C constructors, methods, and nested classes is part of the run-time representation of class C

27 December 2019 OSU CSE 24

Page 25: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Example Class Cpublic class C implements cInterface {

private static String sVar;private int iVar;

public C(String s, int i) {

C.sVar = s;

this.iVar = i;

}

public static void sMethod(...) {...}public void iMethod(...) {...}

}

...

cInterface x1 = new C("foo", 1);

cInterface x2 = new C("bar", 2);

27 December 2019 OSU CSE 25

Page 26: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Example Class Cpublic class C implements cInterface {

private static String sVar;private int iVar;

public C(String s, int i) {

C.sVar = s;

this.iVar = i;

}

public static void sMethod(...) {...}public void iMethod(...) {...}

}

...

cInterface x1 = new C("foo", 1);

cInterface x2 = new C("bar", 2);

27 December 2019 OSU CSE 26

The relevant info for upcoming run-time pictures is the part

shown in red.

Page 27: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Run-Time Picture

27 December 2019 OSU CSE 27

1 2

"bar"

instanceofinstanceof

Page 28: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Run-Time Picture

27 December 2019 OSU CSE 28

1 2

"bar"

instanceofinstanceof

There is a run-time representation of each class that

holds all its static variables.

Page 29: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Run-Time Picture

27 December 2019 OSU CSE 29

1 2

"bar"

instanceofinstanceof

Type erasure: the picture would be

the same even if Cwere generic, say C<T>, and x1 and x2 had different T.

Page 30: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Run-Time Picture

27 December 2019 OSU CSE 30

1 2

"bar"

instanceofinstanceof

Surprise! This means that even if C were generic,

there would still be only one “copy” of

sVar.

Page 31: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Run-Time Picture

27 December 2019 OSU CSE 31

1 2

"bar"

instanceofinstanceof

There is a run-time representation of

each instance that holds all its instance

variables.

Page 32: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Run-Time Picture

27 December 2019 OSU CSE 32

1 2

"bar"

instanceofinstanceof

Each instance “knows” its dynamic

type at run-time.

Page 33: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Static Initialization Blocks

• To initialize static variables in a class, you may write a static initialization block that looks like this:static {

// Code to initialize static variables

}

• This code is automatically executed when the class is loaded, i.e., once at the very beginning of program execution

27 December 2019 OSU CSE 33

Page 34: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Nested Interfaces

• An interface may be nested within another interface– Example (from OSU CSE components)Map.Pair<K,V>

– Example (from Java libraries)Map.Entry<K,V>

27 December 2019 OSU CSE 34

Page 35: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Nested Classes

• A class that is nested as a member of another class may be:– A static nested class– An instance nested class, which is called an

inner class

27 December 2019 OSU CSE 35

Page 36: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Static Nested Class

• A static nested class does not have access to instance members of its enclosing class– Effectively, it’s a top-level class declared

inside another class since it “logically belongs”

– Example (from OSU CSE components):MapSecondary.SimplePair<K,V>

– Example (from Java libraries):AbstractMap.SimpleEntry<K,V>

27 December 2019 OSU CSE 36

Page 37: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Inner Class

• Each instance of an inner class belongs to an instance of its enclosing class– Has access to generic parameters, variables,

methods, etc., of its enclosing instance– Examples (from OSU CSE components):

Stack2.Node

Stack2.Stack2Iterator

27 December 2019 OSU CSE 37

Page 38: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Run-Time Picture

27 December 2019 OSU CSE 38

2

6

data

18

data

next nextthis

Page 39: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Run-Time Picture

27 December 2019 OSU CSE 39

2

6

data

18

data

next next

These two instances of Node“belong to” the Stack2

instance that created them.

this

Page 40: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Access Modifiers

• There are four access modifiers in Java. In decreasing order of visibility (but not presented in this order on the following slides), they are:– public– protected– default (“package private”)– private

27 December 2019 OSU CSE 40

Page 41: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Access Modifiers

• There are four access modifiers in Java. In decreasing order of visibility (but not presented in this order on the following slides), they are:– public– protected– default (“package private”)– private

27 December 2019 OSU CSE 41

Only public and “package private” apply to top-level units, i.e., interfaces and

classes; interface memberscan be public (the default) or private (not used in OSU

components); class memberscan be any of the four.

Page 42: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

public• A top-level unit declared public is

accessible from anywhere– So long as it is in scope, e.g., via import,

which henceforth goes without saying• A member declared public is accessible

from anywhere– So long as the top-level unit it’s in is also

accessible, which henceforth goes without saying

27 December 2019 OSU CSE 42

Page 43: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Default (“Package Private”)• A top-level unit declared without any

access modifier is accessible from anywhere within the same package– The default is also called package private

accessibility (though probably it should be called “package public”)

• A class member declared without any access modifier is accessible from anywhere within the same package

27 December 2019 OSU CSE 43

Page 44: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Default (“Package Private”)• A top-level unit declared without any

access modifier is accessible from anywhere within the same package– The default is also called package private

accessibility (though probably it should be called “package public”)

• A class member declared without any access modifier is accessible from anywhere within the same package

27 December 2019 OSU CSE 44

This offers little protection against unintended access, because anyone

can declare their class to be in a given package (e.g., pkg) simply by

adding this as its first line:package pkg;

Page 45: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Default (“Package Private”)• A top-level unit declared without any

access modifier is accessible from anywhere within the same package– The default is also called package private

accessibility (though probably it should be called “package public”)

• A class member declared without any access modifier is accessible from anywhere within the same package

27 December 2019 OSU CSE 45

Recall: an interface memberdeclared without any access modifier

is public

Page 46: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

protected• A class member declared protected is

accessible from within any subclass, andfrom anywhere in the same package

• Example: the JUnit test fixture pattern in which there is a protected method wrapping each constructor of the UUT (which is meant to be overridden in a subclass specific to that UUT)

27 December 2019 OSU CSE 46

Page 47: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

protected• A class member declared protected is

accessible from within any subclass, andfrom anywhere in the same package

• Example: the JUnit test fixture pattern in which there is a protected method wrapping each constructor of the UUT (which is meant to be overridden in a subclass specific to that UUT)

27 December 2019 OSU CSE 47

So, like the default, this offers little protection against unintended access

(despite its optimistic name).

Page 48: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

private• A class (or interface) member declared private is accessible only from within the class (or interface) containing the privatemember

• Best practice is to make all members in interfaces public and all static and instance variables in classes private, and to offer public methods with which clients may indirectly manipulate their values– An exception: constants, which are normally public static final variables

27 December 2019 OSU CSE 48

Page 49: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

The Many Meanings of “Final”• A class declared final may not be

extended• A method declared final may not be

overridden• A variable declared final may not be

modified once it is given a value– Which is why it is often called a “constant”

• A formal parameter declared final may not be modified inside the method

27 December 2019 OSU CSE 49

Page 50: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

The Many Meanings of “Final”• A class declared final may not be

extended• A method declared final may not be

overridden• A variable declared final may not be

modified once it is given a value– Which is why it is often called a “constant”

• A formal parameter declared final may not be modified inside the method

27 December 2019 OSU CSE 50

Be careful! For a reference variable (or parameter):the reference value cannot be modified, but

the object value can be modified!

Page 51: Java Loose Ends - Computer Science and Engineeringweb.cse.ohio-state.edu/.../33.Java-Loose-Ends.pdf• There are four access modifiers in Java. In decreasing order of visibility (but

Resources• The Java Tutorials: Exceptions

– http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

• The Java Tutorials: Understanding Instance and Class Members– http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

• The Java Tutorials: Nested Classes– http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

• The Java Tutorials: Controlling Access to Members of a Class– http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

27 December 2019 OSU CSE 51