Top Banner
Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hu n [email protected]. kr * This transparency is based on that made by G. Fox and B. Carpenter in Florida State University and lecture note of Weiss
40

Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun [email protected] * This transparency is based on that made by.

Jan 01, 2016

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Introduction to the Java Programming Language

- Part 3 -

Instructor : An, Seung [email protected]

* This transparency is based on that made by G. Fox and B. Carpenter in Florida State University and lecture note of Weiss

Page 2: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Checkpoint

• Part 1– Basic Concept & Language Philosophy

• Part 2 & 3– Java Language Basics– Classes, Instances & Methods By here!!

• Part 4– Inheritance and Class hierarchy

• Part 5– Exception & Package

• How much do you understand??• Did you install JDK?

Page 3: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Basic Example on your Text

• First Program

javac FirstProgram.java java FirstProgram

Page 4: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Example for operator

Page 5: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Example for Method declaration

Page 6: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Example for Reference(1/2)

Page 7: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Example for Reference(2/2)

Page 8: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Example for Array(1/2)

Page 9: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Example for Array(2/2)

(a) int []original = arr;(b) arr = new int [12];(c) for(int i = 0; i<10; I++)

arr[I] = original[i];(d) Original = null;

Page 10: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Example for Class(1/2)

Page 11: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Example for Class(2/2)

Page 12: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Example for Class(3/3)

Page 13: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

The Java Object Model: Inheritance and the Class

Hierarchy

Page 14: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

• Use– A uses B: the most informal and general relation. A

might, for example, call a method from class B, or have a method with argument type B or return type B.

• Containment– A has a B: an important special case of use—class A

has a field of type B.

• Inheritance– B is an A: class B has all the properties of class A.

The compiler treats B as a special case of A, and allows an instance of B to be used in any place where an instance of A could appear. In general the class B will extend A with some extra properties of its own.

Some Dependencies between Classes

Page 15: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Inheritance

• The inheritance relation is (unexpectedly?) powerful; it is built into all fully object-oriented languages.

• In Java, if some class A has been defined, we can subsequently declare a new class, B, and specify that it extends A.

• Class A is called the superclass of B. Class B is a subclass of A.• The class B is automatically given (inherits) all the fields and me

thod definitions of A. Further fields and methods can be added that are specific to B.

• In particular, for every method signature in class A, class B will have a method with identical signature.

Crucially, though, the class B may define a different the implementation for some of those methods.

Page 16: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Trivial use of Inheritanceclass Shape { void setColor(Color color) {this.color = color ; } Color color ; int x, y ; // position of center, say }

class Circle extends Shape { void drawCircle() {. . .} double radius ; }

class Rectangle extends Shape { void drawRectangle() {. . .} double height, width ; }

• Subclasses automatically inherit color, x, y fields of Shape, and setColor() method.

Page 17: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

A Limited Kind of Polymorphism

void setAllColors(Shape [] shapes, Color color) { for(int i = 0 ; i < shapes.length ; i++) shapes [i].setColor(color) ; }

Shape [] bag = new Shape [N] ;

bag [0] = new Circle() ; bag [1] = new Rectangle() ; . . . setAllColors(bag, Color.red) ; . . .

• The function setAllColors works on a collection of shapes, and works correctly independently of whether each shape is actually a Circle or a Rectangle.

Page 18: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Class Hierarchies

• Class hierarchy diagrams represent inheritance relations between classes:

Class: Shape

Class:Circle

Class:Rectangle

These diagrams become more complex as subclasses are further extended. But they are always trees, because in Java each subclass has a single superclass.

Page 19: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Inheritance with Overriding

class Shape { void draw() {} Color color ; int x, y ; }

class Circle extends Shape { void draw() {. . .} double radius ; } class Rectangle extends Shape { void draw() {. . .} double height, width ; }

• Subclasses override the definition of draw() in the superclass.

• Bodies of methods contain the actual code for drawing a circle or rectangle, respectively.

Page 20: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

True Polymorphism

void drawAll(Shape [] shapes) { for(int i = 0 ; i < shapes.length ; i++) shapes [i].draw() ; }

Shape [] bag = new Shape [N] ;

bag [0] = new Circle() ; bag [1] = new Rectangle() ; . . . drawAll(bag) ;

• The draw() method invoked is the method defined in the class of the referenced object (Circle or Rectangle).– not the implementation defined in the compile-time type of the varia

ble, namely Shape.

• drawAll() correctly draws a mixed bag of shapes whose details may be unknown when this method is written.

Page 21: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Runtime Lookup of Methods

class Shape { void draw() {. . .} }

Square s = new Square() ;s.draw() ;

class Square extends Rectangle { // No declaration of draw()}

class Rectangle extends Shape { void draw() {. . .}}

class Circle extends Shape { void draw() {. . .}}

Search up the inheritancetree until find firstclass that defines method.

Page 22: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Inherited Methods and Overriding

• The method associated with the actual class of the instance is called, even if it invoked from code in the superclass.

• Suppose we add a drawInColor() method to Shape: class Shape { void draw() {}

void drawInColor(Color color) { this.color = color ; draw() ; } Color color ; int x, y ; }

• The implementation of drawInColor() is inherited by the subclasses. But when it is invoked on one, their own draw() methods are called! More polymorphism.

Page 23: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Abstract Methods and Classes• In our example, the draw() method in the Shape class did nothin

g. It may not be necessary to give a implementation of this method in the base class at all, because it may be that it is only ever invoked on instances of subclasses representing concrete shapes (as here).

• In this situation, the superclass and unimplemented methods can be declared abstract:

abstract class Shape { //abstract class abstract void draw() ; // abstract method

Color color ; int x, y ; }

– It is not possible to create instances of abstract classes. One must create a subclass that overrides all abstract methods of the base class, giving implementations.

Page 24: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Final Methods and Classes• If a method is declared final, it may not be

overridden in subclasses (opposite extreme to abstract, which must be overridden!)

• If we declared draw() in Rectangle to be final, we could never give a more specialized draw() in a subclass:

class Rectangle extends Shape { final void draw() {. . .} // final method double height, width ; }

class Square extends Rectangle { void draw() {. . .} // Compile-time

error!! }

– In places where the compiler can tell that a final method will be called, it can produce optimized code to avoid overheads of “late binding”.

• A final class cannot be extended.

Page 25: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Protected Access• By default a field or method of a class can be access

ed by any code appearing in the same package.– Packages are discussed later.

• The access modifier protected on a field or method means that this member can also be accessed by any subclass of the class in which it is declared.

• Note this modifier increases accessibility from the default. . .– . . . because a subclass may be declared outside the packag

e that contains the superclass.– Least accessible members are private (visible in declaring cla

ss only), followed by default (declaring package only), followed by protected (package and subclasses), followed by public (visible everywhere).

Page 26: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

The Universal Superclass—Object

• The Java language provides a superclass for all other classes. If no extends clause is given in a class definition, the class implicitly extends Object.

• Array types are also considered to extend Object.

• A variable of type Object can hold a reference to any object or array.

• Strictly speaking, Object is the root of every inheritance diagram.

Page 27: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Methods on the Object class

Public class Object {

public final Class getClass() { . . . } // Basis for reflection.

public String toString() { . . . } //A String representation

public boolean equals(Object obj) { . . . } // Equality test

public int hashcode() { . . . } // For use by hash tables

protected Object clone() throws . . . { . . . } // Bit by bit copy

public final void wait() throws . . . { . . . } // Deschedule this thread public final void wait(long millis) throws . . . { . . . } public final void wait(long millis, int nanos) throws . . . { . . . }

public final void notify() throws . . . { . . . } // Reschedule any . . . public final void notifyAll() throws . . . { . . . } // . . . or all threads.

protected void finalize() throws . . . { . . . } // invoked by GC.}

Page 28: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Reference Conversions

• Conceptually, we saw, an instance of a subclass “is an” instance of the superclass.

• Hence one can assign a reference to a subclass object to a variable of a superclass type.

• Concretely, this implies a conversion from a subclass type to a superclass type is regarded as a kind of widening conversion.– Recall widening conversions are allowed implicitly in various context

s.

• Narrowing conversions on reference types go the other way—from a superclass down to some subclass.– Narrowing conversions require an explicit cast.

• Good programming practice minimizes use of narrowing conversions, but sometimes they are necessary.

Page 29: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Simple Collections

• The package java.util contains a family of collection classes.

• Here we will only mention two of the most widely used:– Vector, and– Hashmap.

• Note Vector is supposed eventually to be superceded by ArrayList.– Consider using ArrayList in your future programs, b

ut Vector is so widespread we describe it here.

Page 30: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

A Vector is Like an Array

• A Vector can be used essentially like an ordinary array.• It has a well-defined current size, returned by the size

() inquiry.• This can be set with setSize(), but usually a Vector is

grown dynamically using methods on next slide.• Vector stores all elements as if the have type Object• If 0 < idx < size(), the methods:

void set(int idx, Object obj) Object get(int idx)

respectively assign and retrieve value of element idx.

Page 31: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

A Vector can Grow and Shrink

• Typically one grows a vector by adding a new element at the end with: void addElement(Object obj)

Causes size() to be incremented by 1.• An arbitrary element can be removed by

Object remove(int idx)

This method causes higher elements to be shifted down one place, and size() to be decremented by 1.

• An element can be inserted in an arbitrary place by insertElementAt(Object obj, int idx)

Element at idx and higher are shifted up one place, and size() is incremented by 1.

Page 32: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Using Vector

void drawAll(Vector shapes) { for(int i = 0 ; i < shapes.size() ; i++) ( (Shape) shapes.get(i) ).draw() ; // Narrowing conversion }

Vector bag = new Vector() ; bag.addElement(new Circle()) ; // Widening conversion bag.addElement(new Rectangle()) ; . . . drawAll(bag) ;

• For polymorphism, Vector stores items in Object references. Hence, get() returns an Object, which usually needs to be cast back to a more specific type.

• If the referenced object is not an instance of the type in the cast, a run-time ClassCastException occurs.

Page 33: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

A HashMap is an Associative Array

• For future reference, we also discuss HashMap here• A HashMap is similar to a vector, but the “index” is an arbitrary o

bject—very commonly a string.• This index is now called a “key”.• In simple cases you create a HashMap with the no-argument con

structor, then put key-value pairs in it using Object put(Object key, Object obj)

(returns old value if key was already in the table).

• Retrieve the element currently indexed by key by: Object get(Object key)

• Remove the element currently indexed by key by: Object remove(Object key)

Page 34: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Using HashMap

HashMap table = new HashMap() ;

table.put(“red”, “stop”) ; table.put(“green”, “go”) ;

String s = (String) table.get(“red”) ; // returns “stop” String t = (String) table.remove(“green”) ;// returns “go” String u = (String) table.get(“green”) ; // returns null

Page 35: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Widening Conversions on Arrays

• There is a widening conversion between two array types if there is a widening reference conversion between their component types.

• This is useful, but can lead to anomalies if used carelessly:Circle [] bag = new Circle [N] ;setAll(bag) ; // Widening: Circle [] to Shape []. // OK at compile-time.

void setAll(Shape [] shapes) { shapes [0] = new Circle() ; shapes [1] = new Rectangle() ; // Widening: Rectangle to Shape. // But throws ArrayStoreException . . . // if invoked as above!}

• Effect would be to assign Rectangle to array of Circles. Requires the compiler to add a new kind of run-time check.

Page 36: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Overloading with Inheritance

void foo(Object p) {. . .} // Signature Ivoid foo(Shape p) {. . .} // Signature IIvoid foo(Object p, Shape q) {. . .} // Signature IIIvoid foo(Shape p, Object q) {. . .} // Signature IV

Object o ;Shape s ;Circle c ;

foo(o) ; // Exact match—use Signature I.

foo(c) ; // Do widening conversion of c to Shape, and use // Signature II—unique “most specific” case.

foo(o, c) ; // Uses Signature III—only case applicable by // widening conversions.

foo(s, s) ; // Compile time error! Signatures III and IV // are both applicable but neither is more specific // than the other!

Page 37: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Overload Resolution across Classes

class Shape { void foo(Circle q) {. . .} // Signature I } class Circle extends Shape { void foo(Shape q) {. . .} // Signature II }

Shape s ; Circle c ;

s.foo(c) ; // Uses Signature I—exact match.

c.foo(c) ; // Compile time error! Signatures I and II // are both applicable but neither is more specific // than the other!

• In compile-time overload resolution (choice of signature), the prefix object expression is treated on the same footing as an extra argument.

Page 38: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Summary: Overloading vs. Overriding

• Resolution of overloading occurs at compile time. The compiler chooses a unique method signature out of several different signatures available (or flags a compile time error if it cannot).

• Overriding occurs in the context of a single signature. In general, if the class hierarchy contains several definitions with identical method signatures, the appropriate definition is chosen at run time.

• Within the body of a class that overrides a method, the method from the superclass can be invoked instead by using the super prefix.

Page 39: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Constructors and Inheritance

• Constructors of subclasses must invoke a constructor of their superclass, to initialize the fields there.

• If a superclass constructor is not explicitly invoked, the no-argument constructor of the superclass is called, implicitly, by the compiler.– A compile-time error is flagged if no such constructor exists.

• If any superclass constructor other than the no-argument constructor is required, it must be invoked explicitly.

• In this case the first statement of a subclass constructor is an explicit constructor invocation using the name super.

Page 40: Introduction to the Java Programming Language - Part 3 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by.

Superclass Constructor Invocationclass Shape { public Shape(Color color, int x, int y) { this.color = color this.x = x ; this.y = y ; } Color color ; int x, y ; }class Circle extends Shape { public Circle(Color color, int x, int y, double radius) { super(color, x, y) ; // superclass constructor invocation

this.radius = radius ; } double radius ;}