Java Loose Ends 27 December 2019 OSU CSE 1 What Else? A few - - PowerPoint PPT Presentation

java loose ends
SMART_READER_LITE
LIVE PREVIEW

Java Loose Ends 27 December 2019 OSU CSE 1 What Else? A few - - PowerPoint PPT Presentation

Java Loose Ends 27 December 2019 OSU CSE 1 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


slide-1
SLIDE 1

Java Loose Ends

27 December 2019 OSU CSE 1

slide-2
SLIDE 2

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

slide-3
SLIDE 3

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

slide-4
SLIDE 4

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

slide-5
SLIDE 5

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

slide-6
SLIDE 6

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 skipped
  • 2. The catch clauses are examined top to bottom for the

first matching catch

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

slide-7
SLIDE 7

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

slide-8
SLIDE 8

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.

slide-9
SLIDE 9

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

  • f memory for this

application.

slide-10
SLIDE 10

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

slide-11
SLIDE 11

Hierarchy of Classes

27 December 2019 OSU CSE 11

Error Exception Throwable

slide-12
SLIDE 12

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

slide-13
SLIDE 13

Hierarchy of Error Classes

27 December 2019 OSU CSE 13

Error Exception Throwable AssertionError VirtualMachine- Error OutOfMemory- Error

slide-14
SLIDE 14

Hierarchy of Error Classes

27 December 2019 OSU CSE 14

Error Exception Throwable AssertionError VirtualMachine- Error OutOfMemory- Error

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

slide-15
SLIDE 15

Hierarchy of Error Classes

27 December 2019 OSU CSE 15

Error Exception Throwable AssertionError VirtualMachine- Error OutOfMemory- Error

There are many more subclasses of Error!

slide-16
SLIDE 16

Hierarchy of Exception Classes

27 December 2019 OSU CSE 16

Error Exception Throwable AssertionError VirtualMachine- Error OutOfMemory- Error Runtime- Exception IOException

IndexOutOf- BoundsException

NullPointer- Exception Arithmetic- Exception

slide-17
SLIDE 17

Hierarchy of Exception Classes

27 December 2019 OSU CSE 17

Error Exception Throwable AssertionError VirtualMachine- Error OutOfMemory- Error Runtime- Exception IOException

IndexOutOf- BoundsException

NullPointer- Exception Arithmetic- Exception

There are many more subclasses of Exception, RuntimeException, and IOException!

slide-18
SLIDE 18

Hierarchy of Exception Classes

27 December 2019 OSU CSE 18

Error Exception Throwable AssertionError VirtualMachine- Error OutOfMemory- Error Runtime- Exception IOException

IndexOutOf- BoundsException

NullPointer- Exception Arithmetic- Exception

With RuntimeException and its subclasses, something is wrong with your program.

slide-19
SLIDE 19

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

slide-20
SLIDE 20

Unchecked vs. Checked

27 December 2019 OSU CSE 20

Exception Throwable Runtime- Exception IOException

IndexOutOf- BoundsException

NullPointer- Exception Arithmetic- Exception Error AssertionError VirtualMachine- Error OutOfMemory- Error

slide-21
SLIDE 21

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

slide-22
SLIDE 22

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

slide-23
SLIDE 23

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.

slide-24
SLIDE 24

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

slide-25
SLIDE 25

Example Class C

public 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

slide-26
SLIDE 26

Example Class C

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

slide-27
SLIDE 27

Run-Time Picture

27 December 2019 OSU CSE 27

1 2 "bar" instanceof instanceof

slide-28
SLIDE 28

Run-Time Picture

27 December 2019 OSU CSE 28

1 2 "bar" instanceof instanceof There is a run-time representation of each class that holds all its static variables.

slide-29
SLIDE 29

Run-Time Picture

27 December 2019 OSU CSE 29

1 2 "bar" instanceof instanceof Type erasure: the picture would be the same even if C were generic, say C<T>, and x1 and x2 had different T.

slide-30
SLIDE 30

Run-Time Picture

27 December 2019 OSU CSE 30

1 2 "bar" instanceof instanceof Surprise! This means that even if C were generic, there would still be

  • nly one “copy” of

sVar.

slide-31
SLIDE 31

Run-Time Picture

27 December 2019 OSU CSE 31

1 2 "bar" instanceof instanceof There is a run-time representation of each instance that holds all its instance variables.

slide-32
SLIDE 32

Run-Time Picture

27 December 2019 OSU CSE 32

1 2 "bar" instanceof instanceof Each instance “knows” its dynamic type at run-time.

slide-33
SLIDE 33

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

slide-34
SLIDE 34

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

slide-35
SLIDE 35

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

slide-36
SLIDE 36

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

slide-37
SLIDE 37

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

slide-38
SLIDE 38

Run-Time Picture

27 December 2019 OSU CSE 38

2 6 data 18 data next next this

slide-39
SLIDE 39

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

slide-40
SLIDE 40

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

slide-41
SLIDE 41

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 members can be public (the default) or private (not used in OSU components); class members can be any of the four.

slide-42
SLIDE 42

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

slide-43
SLIDE 43

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

slide-44
SLIDE 44

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;

slide-45
SLIDE 45

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 member declared without any access modifier is public

slide-46
SLIDE 46

protected

  • A class member declared protected is

accessible from within any subclass, and from 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

slide-47
SLIDE 47

protected

  • A class member declared protected is

accessible from within any subclass, and from 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).

slide-48
SLIDE 48

private

  • A class (or interface) member declared

private is accessible only from within the class (or interface) containing the private member

  • 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

slide-49
SLIDE 49

The Many Meanings of “Final”

  • A class declared final may not be

extended

  • A method declared final may not be
  • verridden
  • 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

slide-50
SLIDE 50

The Many Meanings of “Final”

  • A class declared final may not be

extended

  • A method declared final may not be
  • verridden
  • 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!

slide-51
SLIDE 51

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