Java the core language What it looks like

  • Slides: 37
Download presentation
Java: the core language • What it looks like: class Once. Again { public

Java: the core language • What it looks like: class Once. Again { public static void main (String[] args){ int X = 1234; System. out. println (“we’ve seen this before”); } } • A superficial resemblance to C++

References • • • Formal definition: Gosling, Joy & Steele White paper (early draft):

References • • • Formal definition: Gosling, Joy & Steele White paper (early draft): Gosling Cornell & Horstmann : Core Java 10, 000 other books Java is work in progress: no ISO standard in sight

white paper buzzwords (Gosling et al) • • • Simple Object-Oriented Distributed Robust Secure

white paper buzzwords (Gosling et al) • • • Simple Object-Oriented Distributed Robust Secure Architecture neutral • • Portable Interpreted High Performance Multithreaded

Core language • Imperative, procedural language • Object-oriented: inheritance is central • Garbage-collected •

Core language • Imperative, procedural language • Object-oriented: inheritance is central • Garbage-collected • conventional control structures • Exceptions and event-handling • concurrency * can’t really be simple will al that. . .

The type model: primitive types and classes • Conventional primitive types with value semantics:

The type model: primitive types and classes • Conventional primitive types with value semantics: int, short, long, byte, float, double, char, boolean • int Value = 123; • char Big. A = ‘A’; • Language defines size of numeric types (eg int is 4 bytes) • char is Unicode (16 bits) • char badkspace = u 0008; • Some implicit conversions on numeric operations

Classes • The basic abstraction mechanism • A long lineage: – Simula (algol derivative

Classes • The basic abstraction mechanism • A long lineage: – Simula (algol derivative with concurrency) – Smalltalk (fully dynamic, class is everything) – Eiffel (hybrid) – C++ (Hybrid, multiple inheritance) – CLOS (dynamic, multiple inheritance)

Class encapsulates data and code Public class counter { counter (int init) { value

Class encapsulates data and code Public class counter { counter (int init) { value = init; } counter () { value = 0; }; public int val () { return value; }; public void incr () { value = value + 1; ); private int value; }

Contrast with Ada • A package contains both type declarations and subprogram declarations (like

Contrast with Ada • A package contains both type declarations and subprogram declarations (like a class) • Related types can appear in the same package (unlike a class) • A package is not a type (unlike a class) • Class unifies (or confuses) the notion of package and type

OO terminology • An object is an instance of a class • A method

OO terminology • An object is an instance of a class • A method defines a message that the object can receive • A message is received by a particular object at run -time • Within a method, the current object is called this – if X is local data, a reference to X is equivalent to this. X

Using a class Test. Counter { counter c 1 = new counter (); counter

Using a class Test. Counter { counter c 1 = new counter (); counter c 2 = c 1; // an alias of c 1. incr(); // call with implicit parameter c 1) if (c 1. val() > 0) c 2. incr(); }; }

Is everything an object? • Only in Smalltalk (even classes!) • Often necessary to

Is everything an object? • Only in Smalltalk (even classes!) • Often necessary to define data and methods without any explicit object to which they belong public class Math { public static double sqrt (double X); public static final double PI = 3. 14159265; } can then write X = Math. sqrt (Y * Math. PI);

Classes are not enough • Need other tools for large program structuring • Packages:

Classes are not enough • Need other tools for large program structuring • Packages: group of classes, with privileged visibility • Mimics directory structure of OS – package My. Graphics; // locus for current class – import java. io. *; // get access to all classes therein – public class Polygons { … } // in My. Graphics • Interfaces: abstract classes

Predefined packages • A large built-in programming environment – java. lang: Object, String, Math…

Predefined packages • A large built-in programming environment – java. lang: Object, String, Math… – java. awt: graphical interface – java. awt. event : interaction with devices – java. applet: the web – java. io: stream and file manipulation – java. util: data and time – java. net: communications

Java is a high-level language • User does not concern itself with the size

Java is a high-level language • User does not concern itself with the size of objects. Storage management is controlled by the system • Garbage collection must be safe: user cannot manipulate addresses directly, language cannot have pointers. • No need for destructors or free commands • Garbage collection is unpredictable: unsuitable for real-time applications

Can you program without pointers? • Pointers are implicit: objects and array have reference

Can you program without pointers? • Pointers are implicit: objects and array have reference semantics class List { int value; List next; } primitive types have value semantics

Value/Reference semantics int x, y; x = y; // value copy y = y

Value/Reference semantics int x, y; x = y; // value copy y = y + 1; // x is unaffected counter c 1, c 2; c 2 = c 2; // value sharing: denote same object c 2. incr(); // c 1 is modified as well int table 1 [], table 2 []; table 1 = table 2; // reference semantics also Equality works like assignment (value /reference)

Value/reference choices • Ada : reference requires explicit access types. Arrays have value semantics

Value/reference choices • Ada : reference requires explicit access types. Arrays have value semantics • C++ : structs have value semantics • SETL : all types have value semantics • pure LISP : functional with no side-effects, no assignment, value semantics with implicit sharing for efficiency

Arrays and Strings • Impractical to make them classes: standard semantics across languages, need

Arrays and Strings • Impractical to make them classes: standard semantics across languages, need efficient implementation int table []; // variable definition table = new int(100); // object allocation • Indexing from zero. Index always checked against bounds

Multidimensional arrays and aggregates • Multidimensional arrays are arrays of arrays int[][] matrix =

Multidimensional arrays and aggregates • Multidimensional arrays are arrays of arrays int[][] matrix = ({ 2, 4, 6}, {3, 6, 9}, 1, 2, 3}}; matrix [2][2] = 0; matrix [3][3] = 100; // will raise exception

Strings • Could be arrays (unification or confusion? ) • Instead, special syntax •

Strings • Could be arrays (unification or confusion? ) • Instead, special syntax • Many special-purpose operations String message = “ what’s new? ”; message = message. substring (0, 6) + “up doc? ”; Note: only operator overloading in Java, no userdefined overloading (reaction to C++)

Strings are constants • Need separate class for mutable strings: • class String. Buffer:

Strings are constants • Need separate class for mutable strings: • class String. Buffer: public int length (); // also strings and arrays public int capacity () public synchronized char. At (int index) public synchronized void set. Char. At (int index, char ch);

Inheritance • Programming by extension and specialization: • A class refines an existing class

Inheritance • Programming by extension and specialization: • A class refines an existing class by adding data members and methods, and redefining methods • What is not redefined is inherited class Point { int x = 0; int y = 0; …}; class Pixel extends Point { int R, G, B; …};

Polymorphism • A variable of a given class can denote an • instance of

Polymorphism • A variable of a given class can denote an • instance of any descendant of the class: class Root… class Better extends Root … class Best extends Better… Root thing = new Root (); . . Thing = new Best (. . ); // ok

Dynamic Dispatching • If class Root has method Mangle, then all its descendants either

Dynamic Dispatching • If class Root has method Mangle, then all its descendants either inherit or redefine Mangle. • Thing. Mangle(. . ); // what gets executed? • Objects carry run-time identification. The class denoted by the current value of the object determines the method to be called

The power of polymorphism • The functionality of a system can be extended by

The power of polymorphism • The functionality of a system can be extended by adding class extensions. The code that manipulate existing classes does not need to be modified. • Object-oriented programming = inheritance + polymorphism + dynamic dispatching

The mother of all classes • Every class is the extension of another. •

The mother of all classes • Every class is the extension of another. • The root of the class hierarchy is Object • Object has no visible data, and several generally useful methods: boolean equals (Object O); String To. String ();

Mixing classes and primitive types • We want to write a “generic” matrix that

Mixing classes and primitive types • We want to write a “generic” matrix that can have integer or real components. • Can write Object[][] matrix; • but can’t put numeric values in matrix because ints are not objects. • Solution: wrapper classes matrix [0][0] = new Integer (5);

Wrapper classes • Integer, Float, Double, Boolean • Constructors, conversion operations, etc. • No

Wrapper classes • Integer, Float, Double, Boolean • Constructors, conversion operations, etc. • No overloading: Integer I 1, I 2, I 3; • can’t write: • I 1 = I 2 + I 3; • instead I 1 = new Integer (I 2. value + I 3. value);

Class Object and generic programming Object thing; • thing can denote an instance of

Class Object and generic programming Object thing; • thing can denote an instance of any class: compiler cannot check legality of any usage, all checks are at run-time. Object [] bag; • no way to define a homogeneous bag. • The absence of templates/generics is the largest deficiency in the language

A large built-in collection of classes • Object – Font – Component – Container

A large built-in collection of classes • Object – Font – Component – Container • Panel • Applet – Button – label • Layout manager

Superclasses and subclasses Class Root {. . }; Class Better extends Root {…}; Root

Superclasses and subclasses Class Root {. . }; Class Better extends Root {…}; Root thing 1 = new Root (); Object anything = new Better (); anything = thing 1; // ok thing 1 = anything; // illegal thing 1 = (Root)anything; // run-time check

Interfaces • A package spec with no body • An abstract class that can

Interfaces • A package spec with no body • An abstract class that can have multiple implementations • A substitute for genericity public interface Comparable { public boolean Less. Than (Comparable C); public boolean Equals (Comparable C); }

Implementing an interface • Any class that has operations with the right signature can

Implementing an interface • Any class that has operations with the right signature can be said to implement the interface: class Point implements Comparable { int X, Y; public boolean Less. Than (Comparable C) { return X < (Point (C). X; } A class can implement multiple interfaces

Event-Driven programming • Events happen asynchronously (mouse click, button push) • Events are objects:

Event-Driven programming • Events happen asynchronously (mouse click, button push) • Events are objects: – AWTevent • Action. Event • Component. Event – Container. Event, Paint. Event, Window. Event…. . • Events have a source • Events can be handled by designated components

Event-Handling • Delegation-based: source object notifies a registered listener • listener must implement the

Event-Handling • Delegation-based: source object notifies a registered listener • listener must implement the appropriate interface: Interface Mouse. Listener { public void Mouse. Clicked (Mouse. Event e) public void Mouse. Entered (…) public void Mouse. Released (…). . .

A listener class Ringer extends Frame implements Action. Listener { private Button ring; public

A listener class Ringer extends Frame implements Action. Listener { private Button ring; public Ringer () { // constructor ring = new Button (“press here”); ring. add. Action. Listener (this); } public void Action. Performed (Action. Event e) { // play something }

white paper buzzwords (Gosling et al) • • • Simple (no chance) Object-Oriented (definitely)

white paper buzzwords (Gosling et al) • • • Simple (no chance) Object-Oriented (definitely) Distributed (yes) Robust (more than C/C++) Secure (ditto, generic programming less safe) Architecture neutral (the advantage of the JVM) Portable (if standard is developed and followed) Interpreted (performance penalty) High Performance (hope for now) Multithreaded (less than Ada)