27
Overview of Java (continue)

Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Embed Size (px)

Citation preview

Page 1: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Overview of Java (continue)

Page 2: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Announcements

You should have access to your repositories and HW0 If you have problems getting HW0, let me know

If you’ve added this class on or after Jan 26, you need to contact me so that I set up your repository

Always check the Announcements page! 2Spring 15 CSCI 2600, A Milanova

Page 3: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Outline

Overview of Java, continued Last time we covered

Model for variables Type safety Compilation vs. interpretation

This lecture A bit more on type safety Reflection Subtype polymorphism; classes and interfaces

Spring 15 CSCI 2600, A Milanova 3

Page 4: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

A Bit More on Type Safety

Type safety: no operation is ever applied on an object that does not support the operation E.g., a+b where a and b are 2DPoints will be

rejected as + cannot be applied on 2DPoints E.g., a.substring(0,10) cannot be applied if

a is an int Type safety prevents runtime errors --- if an

operation is applied on an object of the wrong type, this almost certainly leads to errors!

Spring 15 CSCI 2600, A Milanova 4

Page 5: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Type Safety

Java ensures type safety with a combination of compile-time (static) and runtime checks Compiler checks and rejects a large number of

programs. E.g., String s = 1 is rejected, String s = new Integer(1) is rejected

Some checks are left for runtime. Can you think of a reason why? E.g., at B b = (B) x; the Java runtime checks if x refers to a B, and throws an Exception if it doesn’t

Spring 15 CSCI 2600, A Milanova 5

Page 6: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Type Safety and Exceptions

Exceptions are good! They prevent application of operations on the wrong type

Object x = new A();B q = (B) x; // ClassCastException // because A is not a Bint case2 = q.foo(1);

The exception prevents execution from reaching q.foo(1) and applying foo(1) on an object (A) that does not have a foo(int)

6

Page 7: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Type Safety

Java is type safe while C++ is type unsafe Java forbids a larger set of errors

E.g., in Java, a[i] will throw an Exception if i is out of the bounds of array a . In C++, a[i] can access arbitrary memory, which can lead to insidious errors!

Thus, it is easier to write correct programs in Java, because the language itself prevent so many errors

7

Page 8: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Reflection

Roughly, the ability of the program to execute code synthesized at runtime. Also, the ability to query metadata about classes

E.g., in JavaScript: eval(string) executes string. string can be arbitrary code synthesized at runtime

Java supports reflection. C++ does not 8

Page 9: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Reflective Object Creation

Standard way to instantiate an object: new Another way: reflective object creation:// First, translate the String argument (the first command-line

// argument in this case) into a Class object:

Class cl = Class.forName(args[0]);

// Next, instantiate the class:

Set s = (Set) cl.newInstance(); The class of the object created here is not known until

runtime! We can specify a java.util.HashSet or a java.util.TreeSet or other at the command line

9

Page 10: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Reflection

Reflection is a very powerful technique Sometimes, we do need to use classes unknown

at compile time Important design patterns use reflection. More on

this later in our class Disadvantages

Awkward code Slows program Prevents optimizations

Spring 15 CSCI 2600, A Milanova 10

Page 11: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Reflection

Avoid using reflection If you have to use, use only object creation, and

access the object through an interface, as shown here:// Translate the string into a Class object:

Class cl = Class.forName(str);

// Instantiate the class:

Set s = (Set) cl.newInstance();

// Access the Set through its interface methods

s.add(something)

// Set is an Interface defined in the Java library

11

Page 12: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Classes and Inheritance

Base class and derived class E.g., in C++: class queue : public list queue is the derived class, list is the base class

In Java: class queue extends list

In Java we say superclass and subclass Other terms are parent class and child class By deriving new classes programmer forms class

hierarchies

12

Page 13: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

13

Subtype Polymorphism

Subtyping and subtype polymorphism – the ability to use a subclass where a superclass is expected Thus, dynamic method binding Advantages? Disadvantages?

In C++ static binding is default, dynamic binding is specified with keyword virtual

In Java dynamic binding is default, static binding is specified with final

Page 14: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

14

Example: Application Draws Shapes on Screen

abstract class Shape { public void draw(); }

class Circle extends Shape { … }

class Square extends Shape { … }

void DrawAll(Shape[] list) {

for (int i=0; i < list.length; i++) {

Shape s = list[i];

s.draw();

}

}

Dynamic dispatch:Call s.draw() resolves at runtime.It can resolve to Circle.draw() or toSquare.draw() depending on what object s refers to. In the static context, we only know of Shape.

Page 15: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Dynamic Method Binding

Dynamic method binding (dynamic dispatch) is the ability to invoke a new, refined method, in a context, where an earlier version is expected

Example on previous slide: s.draw() binds dynamically (i.e., at runtime) to one of Circle.draw() or Square.draw()

Spring 15 CSCI 2600, A Milanova 15

Page 16: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Subtype Polymorphism

Polymorphism is an important concept in programming languages and software Polymorphism means “many forms”

Example on slide 14. DrawAll is polymorphic because it works with many concrete types, Circle, Square, Triangle It’s subtype polymorphism because these

concrete types are related: they are all “subtypes” of Shape

16

Page 17: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Benefits of Subtype Polymorphism

Enables extensibility and reuse! In our example, we can extend the Shape hierarchy

without modifying DrawAll We can reuse Shape and DrawAll Subtype polymorphism enables the

Open/closed principle (credited to Bertrand Meyer)

Software entities (classes, modules) should be open for extension but closed for modification

In other words, it’s easy to extend the code with additional functionality

17Spring 15 CSCI 2600, A Milanova

Page 18: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

18

Benefits of Subtype Polymorphism

abstract class Shape { public void draw(); }

class Circle extends Shape { … }

class Square extends Shape { … }

class Triangle extends Shape { … }

Makes it very easy to extend with a Triangle!

The Java code requires no changes in DrawAll!

It would have been very hard to extend analogous C code!Spring 15 CSCI 2600, A Milanova

Page 19: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

“Science” of software design teaches Design Patterns. A lot on Design patterns later in our class

Design patterns promote design for extensibility and reuse. Maintainable software

Nearly all design patterns make use of subtype polymorphism!

Spring 15 CSCI 2600, A Milanova 19

Benefits of Subtype Polymorphism

Page 20: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

20

Some Differences C++ vs. Java

Access control modifiers – public, private, and others What portion of the class is visible to users ? Public, protected or private visibility Java: Has package is default; protected is slightly different from C++ C++: Has friend classes and functions

Visibility of superclass members C++: a subclass can restrict visibility of superclass members Java: a subclass can neither increase nor restrict visibility of

superclass members Inheritance

C++ allows for multiple inheritance Java allows single class inheritance & multiple interface “inheritance”

E.g., class B extends A implements I, J, K…

Spring 15 CSCI 2600, A Milanova

Page 21: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Subclassing in Java

Subtype polymorphism is achieved by subclassing There is a subtle difference between subtyping and

subclassing. More on this later! Typical subclassing in good Java code:

Subclass an abstract class In our example, Shape is abstract, Circle and Square are

concrete subclasses Implement an interface

Shape is an interface and Circle and Square implement the interface (next slide)

21

Page 22: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

22

An Interface

interface Shape { public void draw(); }

class Circle implements Shape {

// must implement void draw()

public void draw() { … }

… // other methods

}

class Square implements Shape {

public void draw() { … }

… // other methods

}Spring 15 CSCI 2600, A Milanova

Page 23: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Subclassing in Java

Rarely we subclass a concrete class. Subtle issues arise

In homework 0, we had the choice to inherit BallContainer (reuse through inheritance), or to include BallContainer (reuse through composition)

Composition is almost always the better choice!

Spring 15 CSCI 2600, A Milanova 23

Page 24: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Abstract Classes vs. Interfaces in Java

Two mechanisms to define abstract supertypes Abstract classes and Interfaces

Abstract class Can contain implementation for some methods Has at least one empty method A good choice when the concrete subclasses

share implementation

24Spring 15 CSCI 2600, A Milanova

Page 25: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Abstract Classes vs. Interfaces in Java

Interface Cannot contain any implementation, just signatures! E.g., MapEntry from the Java library:

interface MapEntry<K,V> {

boolean equals(Object o);

K getKey();

V getValue();

int hashCode();

V setValue(V value);

}

25Spring 15 CSCI 2600, A Milanova

This is a generic interface, K and V aretype parameters. (Like C++ templates)There is no implementation, all methods are just signatures.

Page 26: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

Abstract Classes vs. Interfaces

public abstract class AbstractMapEntry<K,V>

implements Map.Entry<K,V> {

public abstract K getKey();

public abstract V getValue();

// Implements Map.Entry.equals

@Override

public boolean equals(Object o) {

if (o == this) // much more here…

}

…26

Page 27: Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve

On Tuesday

Reasoning about code and Hoare Logic

Spring 15 CSCI 2600, A Milanova 27