Download (why?) Basic Java Syntax

Document related concepts
no text concepts found
Transcript
Java Programming
Object-Oriented Programing
in Java
Cheng-Chia Chen
Transparency No. 1-1
Basic Java Syntax
Contents








Object and Class
The contents of an object/class
Creating and initializing Objects
Accessing object data and methods
Destroying and finalizing objects
Subclass and inheritance
Interfaces
Java modifiers summary
Transparency No. 1-2
Basic Java Syntax
What is an Object ?
 Real-world objects:
 Concrete objects: Apple1, Car1, TV2, Teacher2,
Student3, …
 Conceptual Objects: 1, 2.3, Date1, Meeting2, point2, …
 Objects have:
 Properties (attributes): color, weight, height, sex, name,
speed, position,…
 Capabilities (behaviors): can receive commands(, request,
query) and respond (do actions) based on its internal
states to change its internal state and/or external
environment.
 The properties of an object constitutes its current
state.
Transparency No. 1-3
Basic Java Syntax
What is a Software object ?
 a software bundle of data and functions used to
model real-world objects you find in everyday life.
 In OOP, Software objects are building block of software systems
 program is a collection of interacting objects
 objects cooperate to complete a task
 to do this, they communicate by sending “messages” to each other
 Software objects can model
 tangible things: School, Car, Bicycle,
 conceptual things: meeting, date
 Processes: finding paths, sorting cards
 Note: Software objects are only abstraction of real-world
objects; properties and behavior of irrelevance will not be
modeled in software objects.
Transparency No. 1-4
Basic Java Syntax
What is a Java Object?
 In Java, an object consists of 0 or more fields and 0 or more
methods.
 Fields are used to model properties.
 Methods are used to model capabilities.
 Fields are variables.
 like the fields of a C struct.
 An object without methods is equivalent to a C struct.
 A method is similar to a C function.
 Normally, it will operate on the fields of the object.
 These fields are accessible by name in the method.
 Java variables can not hold objects, only references to them.
 Object do not have a names.
 Object are created only at runtime.
 Given a reference r to an object, the syntax for accessing a field
is: r.field_name, the syntax for accessing a method
is: r.method()
Transparency No. 1-5
Basic Java Syntax
Classes and Objects
 Current conception:
 a java/software object  a real-life object,
 e.g., a Java car  a real car
 Disadvantage: impractical to work with objects this way
 may be indefinitely many (i.e., modeling all atoms in the universe)
 do not want to describe each individual separately, because they may
have much in common
 Classifying objects into classes of similar
properties/behaviors





factors out commonality among sets of similar objects
lets us describe what is common once
then “stamp out” any number of copies later
Ex: Student: { S1, S2, S3 } Course:{C1,C2,C3} Teacher:{ T1,T2}
but not {s1, t1}, {s2, t2}, {c1,c2,c3,s3}
 Analog:
 stamp
 Imprints
印章 (class)
戳印 (objects)
Transparency No. 1-6
Basic Java Syntax
What is a Java Class?
 In Java, a class is a template (textual
description) of a set of similar objects.
 All objects in the class have the same types of
properties and the same set of capabilities.
 It defines the fields and methods that all
objects in that class will have.
 Classes have names.
 Class appear in the text of your program.
 A java program consists of a set of classes.
 A defined class is a Java Type, so you can
have objects or variables of that type.
Transparency No. 1-7
Basic Java Syntax
Class diagrams
Transparency No. 1-8
Basic Java Syntax
An Example: the class of Circles:
 Properties: a circle can be described
 by the x, y position of its center and
 by its radius.
 Methods: Some useful operations on Circles:




compute circumference,
compute area,
check whether points are inside the circle,
etc.
Transparency No. 1-9
Basic Java Syntax
The Circle class
 By defining the Circle class (as below), we create a new data
type.
// The class of circles (partially defined)
class Circle
{ // Fields
double x, y;
double r;
// Methods
double circumference()
{ return 2 * 3.14159 * r; }
double area()
{ return 3.14159 * r * r ; }
void scale(double multiplier) { r *= multiplier; }
void print() {
System.out.println("circle of radius "+ r +
" with center at (" + x + "," + y + ")“ );
}
}
Transparency No. 1-10
Basic Java Syntax
Creating Objects
 In Java, objects are created by the new operator.
 For example:
//define a variable to refer to Circle objects;no objects yet.
Circle c ; // c is null now
// create a circle object and
c = new Circle();
make the variable refer to it
// define variable and create
Circle d = new Circle();
Circle object all at once
Note: the fields in these objects are given default values at
creation (0 for numbers; null for object references)
Transparency No. 1-11
Basic Java Syntax
Accessing Object Data
 We can access data fields of an object (subject to visibility
restrictions -- see later).
 For example:
// create a new Circle
Circle c = new Circle();
//initialize our circle to have center (2, 5) and radius 1.0.
c.x = 2.0;
c.y = 5.0;
c.r = 1.0;
// create another circle
Circle d = new Circle();
//initialize this circle to have center (10,7)and double the
radius of circle c.
d.x = 10.0;
d.y = 7.0;
d.r = c.r * 2.0;
Transparency No. 1-12
Basic Java Syntax
Using Object Methods
 To access the methods of an object, use same syntax as
accessing the data of an object:
Circle c;
double a;
...
a = c.area(); // Not a = area(c);
Notes
 Each method has a signature, which is defined by:
 The method name and
 The sequence of all types of arguments
 Each class can define several methods with same
name and different types of arguments
(overloading).
Transparency No. 1-13
Basic Java Syntax
Constructors
 Every class in Java has at least one constructor
method, which has the same name as the class.
 The purpose of a constructor is to perform any
necessary initialization for new objects.
 Java provides a default constructor that takes no
arguments and performs no special initialization (i.e.
gives objects default values).
 Note: Java compiler provide the default constructor:
className() only if you do not provide any constructor at
your class definition.
 For example:
Circle c = new Circle();
Transparency No. 1-14
Basic Java Syntax
Defining a Constructor
 Can define additional constructors for initialization.
// The circle class, with a constructor
public class Circle
{ public double x, y, r;
// Constructor method
public Circle(double x, double y, double r)
{
this.x = x;
this.y = y;
this.r = r;
}
// Other methods ... as above
...
}
Transparency No. 1-15
Basic Java Syntax
Defining a Constructor (cont.)
 With the new constructor, we can create and
initialize a Circle object as:
Circle c = new Circle(2.0, 5.0, 1.0);
 A constructor is like a (static) method whose name
is the same as the class name.
 The return value is an instance of the class.
 No return type is specified in constructor
declarations, nor is the void keyword used.
Transparency No. 1-16
Basic Java Syntax
Multiple Constructors
 A class can have any number of constructor methods.
public class Circle
{
public double x, y, r;
// Constructors
public Circle(double x, double y, double r)
{ this.x = x; this.y = y; this.r = r;
}
public Circle(double r)
{ x = 0.0; y = 0.0; this.r = r;
}
public Circle(Circle c)
{ this.x = c.x; this.y = c.y; this.r = c.r;
public Circle()
{ x = 0.0; y = 0.0; r = 1.0;
}
// Other methods ... as above
...
}
Transparency No. 1-17
}
Basic Java Syntax
Multiple Constructors (cont.)
 With the new constructors, we can initialize circle objects as
follows:
Circle c1 = new Circle(2.0, 5.0, 1.0);
// c1 contains (2.0, 5.0, 1.0)
Circle c2 = new Circle(3.5);
// c2 contains (0.0, 0.0, 3.5)
Circle c3 = new Circle(c2);
// c3 contains (0.0, 0.0, 3.5)
Circle c4 = new Circle();
// c4 contains (0.0, 0.0, 1.0)
 All uninitialized data receives default values.
Transparency No. 1-18
Basic Java Syntax
Invoking one constructor from another
 We can use this(…) in a constructor to invoke other
constructor.
public class Circle {
public double x, y, r;
// Constructors
public Circle(double x, double y, double r)
{ this.x = x; this.y = y; this.r = r;
}
public Circle(double r)
//{x =0.0; y = 0.0; this.r = r;} replaceable by
{this(0.0,0.0,r); }
public Circle()
//{x = 0.0; y = 0.0; r = 1.0;} replaceable by
{this(1.0); }
...
}
Note: do not result in recursion.
Transparency No. 1-19
Basic Java Syntax
Object and Object References
 A java object is a memory structure containing both data and
methods
 An object reference holds the memory address of an object
 Rather than dealing with arbitrary addresses, we often depict
a reference graphically as a “pointer” to an object
ChessPiece bishop1 = new ChessPiece();
bishop1
20
Transparency No. 1-20
Basic Java Syntax
Assignment Revisited
 The act of assignment takes a copy of a value and
stores it in a variable
 For primitive types:
int num1 = 5, unm2 = 12;
num2 = num1;
Before
num1
5
After
num2
12
num1
5
num2
5
21
Transparency No. 1-21
Basic Java Syntax
Reference Assignment
 For object references, assignment copies the memory location:
bishop2 = bishop1;
Before
bishop1
bishop2
After
bishop1
bishop2
22
Transparency No. 1-22
Basic Java Syntax
Aliases
 Two or more references that refer to the same object
are called aliases of each other
 One object (and its data) can be accessed using
different variables
 Aliases can be useful, but should be managed
carefully
 Changing the object’s state (its variables) through
one reference changes it for all of its aliases
 Ex:
Circle c = new Circle(1.0, 2.0, 3.0);
Circle d = c; // c and d are aliases.
c.r = 4.0; // d.r == 4.0 now.
23
Transparency No. 1-23
Basic Java Syntax
Destroying Objects
 When an object no longer has any valid references to it,
it can no longer be accessed by the program
 It is useless, and therefore called garbage
 Java performs automatic garbage collection periodically,
returning an garbage object's memory to the system for
future use
 Hence it is needless to explicitly destroy objects.
 How can references to objects '' go away'‘ ?
 Re-assigning object variables (a = b; a = null) or
 object variables (locals or parameters) going out of scope.
 no more malloc/free bugs
Transparency No. 1-24
Basic Java Syntax
Object Finalization
 A constructor method performs initialization for an
object; a Java finalizer method performs finalization
for an object.
 Garbage collection only help freeing up memory.
 But there are other resources needed to be released.
 file descriptors, sockets, lock, database connection.
Transparency No. 1-25
Basic Java Syntax
Example: A Finalizer Method from the Java FileOutputStream class.
/**
* Closes the stream when garbage is collected.
* Checks the file descriptor first to make sure it is not
already closed.
*/
protected void finalize() throws IOException {
if (fd != null) close();
}
Transparency No. 1-26
Basic Java Syntax
Notes about finalize()
 invoked before the system garbage collects the
object.
 no guarantees about when a finalizer will be invoked,
or in what order finalizers will be invoked, or what
thread will execute finalizers.
 After a finalizer is invoked, objects are not freed
right away.
 because a finalizer method may "resurrect" an object by
storing the this pointer somewhere.
 may throw an exception; If an uncaught exception
actually occurs in a finalizer method, the exception
is ignored by the system.
 No ‘class Finalization’ method defined.
Transparency No. 1-27
Basic Java Syntax
Classes v.s. Objects
 two of the most frequently occurring terms in the OO
programmer's vocabulary.
 A class
An object...
 exist at compile time
exists at runtime only
 a template/pattern
created/instantiated from
for objects
a class' specification
 "only exists once"
can be created many times
from one class
 a .java file
returned by the new
operator
 dress pattern
dress
 architectural plans
house
 stamp
imprints
Transparency No. 1-28
Basic Java Syntax
Types of variables and methods in a Java class
 There are two main types of variables/fields:
 instance variables
 class (or static) variables
 Instance variables store information pertaining to one
particular object's state
 Class variables store information pertaining to all objects
of one class
 Likewise, there are two types of methods:
 Instance methods
 Class (static) methods
 Instance methods belong to individual objects; whereas
class methods belongs to the whole class.
 Note: In class method, you cannot use this and instance
variables.(why?)
Transparency No. 1-29
Basic Java Syntax
Class diagram of an Account class.
Class Name
Instance Methods
ShowNumberOfAccount
Class Methods
Transparency No. 1-30
Basic Java Syntax
Declare class field/method with the ‘static’ Modifier
 makes methods and variables belong to the class rather than
instances of the class.
 Example: counting how many circles:
public class Circle
{ public double x, y, r; // instance variables
// ncircles is class variable
public static int ncircles = 0;
// Constructors
public Circle(double x, double y, double r)
{ this.x = x; this.y = y; this.r = r;
ncircles++; }
public Circle(double r)
{ x = 0.0; y = 0.0; this.r = r;
ncircles++; }
...}
Transparency No. 1-31
Basic Java Syntax
The static Modifier (cont.)
 In the above example, there's only one instance of
the ncircles variable per Circle class but one
instance of x, y and r per Circle object.
 Diff. ways to reference ncircles:
 Circle.ncircles // ClassName.classVarName
 ncircles; this.ncircles, // used inside the Circle class
definition only
 c.ncircles // where c is a Circle variable
 Similar approach for static methods.
 Examples of static methods (or called class method):
 Math.cos(x)
Math.pow(x,y)
Math.sqrt(x)
Transparency No. 1-32
Basic Java Syntax
Notes on class methods
 Must be declared with the static keyword
 Also called static method
 Can only operate on class variables (e.g., static)
 Cannot use ‘this’
 Cannot use instance variables
 To access a class method: same as to access class
vars:
 Circle.countCircles() // ClassName.classVarName
 countCircles(); this.countCircles(),

// legal only when inside the Circle class definition
 c.countCircles() // where c is a Circle variable
 Lots of examples of class methods in the JDK (e.g.,
String)
Transparency No. 1-33
Basic Java Syntax
Example: instance member v.s. class member
Class B { int x; static int y;
Int b4() { // instance method
static int b1() { … }
int b2 () { … }
c = x; c = this.x //ok!
static int b3() { … // class method
c = y; c = B.y; c = this.y //ok!
int c;
…
c = x; c = this.y //error
c = y; c = B.y;
//ok!
c = b1(); c = this.b1() // ok
A a = new A();
c = b2(); c=this.b2() // ok
B b = new B();
}
c = a.a1();
//ok!
c = a.a2() ;
// ok!
c = A.a2() ;
// error!
}
c = A.a1() ;
// ok!
c = b.b1() ;
//ok!
c = b.b2() ;
// ok!
Class A {
c = B.b2() ;
// error!
public static int a1(){…}
c = B.b1() ;
// ok!
public int a2() {…} … }
c = b1();
// ok
c = b2();
// error
}
Transparency No. 1-34
Basic Java Syntax
Class and Instance initializers
 Both class and instance variables can have
initializers attached to their declarations.
 static int num_circles = 0;
 float r = 1.0;
 Class variables are initialized when the class is first
loaded.
 Instance variables are initialized when an object is
created.
 Sometimes more complex initialization is needed.
 For instance variables, there are constructor methods ,and
instance initializer.
 For class variables static initializers are provided
Transparency No. 1-35
Basic Java Syntax
An example static/instance initializer
public class TrigCircle { // Trigonometric circle
// Here are our static lookup tables, and their own simple initializers.
static private double sin[] = new double[1000];
static private double cos[] = new double[1000];
// Here's a static initializer "method" that fills them in.
// Notice the lack of any method declaration!
static {
double x, delta_x;
int i;
delta_x = (Circle.PI/2)/(1000-1);
for(i = 0, x = 0.0; i < 1000; i++, x += delta_x) {
sin[i] = Math.sin(x);
cos[i] = Math.cos(x);
} … // The rest of the class omitted.
Transparency No. 1-36
Basic Java Syntax
An example static/instance initializer (continued)
// instance field and methods
Private int[] data = new int[100]; // data[i] = i for i = 0..99
// instance initializer as an unnamed void method
{ for(int I = 0; I <100; I++) data[I] = I; }
…
}
Transparency No. 1-37
Basic Java Syntax
Notes on initializers
 can have any number of static/instance initializers;
 can appear anywhere a field or method can appear.
 Static initializer behaves like class method and
cannot use this keyword and any instance fields of
the class
 The body of each instance initializers (alone with
field initialization expressions) is executed in the
order they appear in the class and is executed at the
beginning of every constructor.
 The body of each static initializers (alone with static
field initialization expressions) is executed in the
order they appear in the class and is executed while
the class is loaded.
Transparency No. 1-38
Basic Java Syntax
Inheritance in OOP
 Inheritance is a form of software reusability in which new
classes are created from the existing classes by absorbing
their attributes and behaviors.
 Instead of defining completely (separate) new class, the
programmer can designate that the new class is to inherit
attributes and behaviours of the existing class (called
superclass). The new class is referred to as subclass.
 Programmer can add more attributes and behaviors to the
subclass, hence, normally subclasses have more features
than their superclasses.
 Inheritance relationships form tree-like hierarchical
structures.
Transparency No. 1-39
Basic Java Syntax
Subclasses and Inheritance
 An important aspect of OO programming:
 the ability to create new data types based on
existing data types
 Example ... a class of drawable Circles:
 we'd like to be able to draw the circles we create, as well
as setting and examining their properties.
 for drawing, we need to know the color of the circle's
outline and its body
 In Java, we implement this by defining a new class that
extends the behavior of the Circle class.
 This new class is a subclass of Circle.
Transparency No. 1-40
Basic Java Syntax
Subclass Example
 The class GraphicCircle:
public class GraphicCircle extends Circle
{ // Extra fields
Color outline, fill;
// Extra constructors
public GraphicCircle(Color edge, Color fill)
{ x = 0.0; y = 0.0; r = 1.0;
outline = edge;
this.fill = fill; }
public GraphicCircle(double r, Color edge, Color fill)
{ super(r); outline = edge; this.fill = fill; }
// Extra methods
public void draw(Graphics g)
{ g.setColor(outline); g.drawOval(x-r, y-r, 2*r, 2*r);
g.setColor(fill);
g.fillOval(x-r, y-r, 2*r, 2*r); }
}
Transparency No. 1-41
Basic Java Syntax
Subclass Inheritance
 A subclass inherits fields and methods from its
parent class.
 A subclass method overrides a superclass method if
they have the same signature.
 A subclass field shadows a superclass field if they
have the same name.
 Refer to the superclass field via super.field
 Note: you can also use super.method(…) to refer
to overridden superclass method.
Transparency No. 1-42
Basic Java Syntax
Using Subclasses
 Subclasses are just like ordinary classes:
GraphicCircle gc = new GraphicCircle();
...
double area = gc.area();
 We can assign an instance of GraphicCircle to a
Circle variable.
 Example:
GraphicCircle gc;
...
...
Circle c = gc; //widening conversion is
// always safe; explicit cast is not needed.
Transparency No. 1-43
Basic Java Syntax
Superclasses, Objects, and the Class Hierarchy
 Every class has a superclass.
 If a class has no extends clause, it extends the
Object class.
 Object Class:
 the only class that does not have a superclass
 methods defined by Object can be called by any Java
object
Transparency No. 1-44
Basic Java Syntax
Abstract Classes
 Abstract class allows us to declare methods
without implementation.
 the unimplemented method is called an abstract method.
 Subclasses can extend abstract class and provide
implementation of all or portion of abstract methods.
 The benefit of an abstract class is that
 methods may be declared such that the programmer
knows the interface definition of an object,
 however, methods can be implemented differently in
different subclasses of the abstract class.
Transparency No. 1-45
Basic Java Syntax
Abstract Classes (cont.)
 Any class containing an abstract method is
automatically abstract itself
 But an abstract class need not have abstract
methods in it!
 an abstract class can not be instantiated
 a subclass of an abstract class can be instantiated if
it overrides each of the abstract methods of its
superclass and provides an implementation for all of
them
 if a subclass of an abstract class does not
implement all of the abstract methods it inherits,
that subclass is itself abstract
Transparency No. 1-46
Basic Java Syntax
Abstract Classes (cont.): an example
public abstract class Shape
{
public abstract double area(); // abstract methods
// to be implemented by subclasses
public abstract double circumference();
}
public class Circle extends Shape
{
protected double r;
protected static final double PI=3.141592653;
public double Circle() { r = 1.0; }
public double Circle(double r) { this.r = r; }
// implementation of two abstract methods of shape class
public double area(){ return PI*r*r; }
public double circumference() { return 2*PI*r; }
public double getRadius() { return r; }
}
Transparency No. 1-47
Basic Java Syntax
Abstract Classes : an example (cont.)
public class Rectangle extends Shape
{ protected double w,h;
// two constructors
public Rectangle() { w=1.0; h=1.0; }
public Rectangle(double w, double h)
{ this.w = w; this.h = h; }
// implementation of two parent methods
public double area() { return w*h; }
public double circumference()
{ return 2*(w + h); }
// methods for this class
public double getWidth() { return w; }
public double getHeight() { return h; }
}
Transparency No. 1-48
Basic Java Syntax
Inheritance revisited
 the concept of inheritance
 the protected modifier
 adding and modifying methods through
inheritance
 creating class hierarchies
1
Transparency No. 1-49
Basic Java Syntax
Inheritance
 Inheritance allows a software developer to derive a new
class from an existing one
 The existing class is called the parent class, or
superclass, or base class
 The derived class is called the child class or subclass.
 The child class inherits characteristics (data & methods)
of the parent class
 That is, the child class inherits the methods and fields
defined for the parent class
2
Transparency No. 1-50
Basic Java Syntax
Inheritance
 Inheritance relationships are often shown graphically in
a class diagram, with the arrow pointing to the parent
class
 Inheritance relationships:
 base class: Vehicle
 derived class: Car
 Car inherits data & methods

from Vehicle
Vehicle
Car
Inheritance should create an is-a relationship, meaning the child
is a more specific version of the parent
51
Transparency No. 1-51
Basic Java Syntax
Deriving Subclasses
 The reserved word extends is used to establish an
inheritance relationship
class Car extends Vehicle {
// class contents
}
 Example: next slide
4
Transparency No. 1-52
Basic Java Syntax
Book
#pages : int = 1500
+pageMessage() : void
Main
+main(in args : String[]) : void
Dictionary
-definitions : int = 5000
+definitionMessage() : void
Transparency No. 1-53
Basic Java Syntax
class Book {
protected int pages = 1500;
public void pageMessage () {
System.out.println ("Number of pages: " + pages);
} // method pageMessage
} // class Book
class Dictionary extends Book {
private int definitions = 52500;
public void definitionMessage () {
System.out.println ("Number of definitions: "+definitions);
System.out.println ("Definitions per page: "
+definitions/pages); // inherited var
} // method definitionMessage
} // class Dictionary
Transparency No. 1-54
Basic Java Syntax
Inheritance Example
class Main { // Test Driver
public static void main (String[] args) {
Dictionary webster = new Dictionary ();
webster.pageMessage(); // inherited method
webster.definitionMessage(); } } // class Words
Transparency No. 1-55
Basic Java Syntax
Controlling Inheritance by the protected Modifier
 The protected (and public) visibility modifier allows a
member of a parent class to be inherited into the child
 But protected visibility provides more encapsulation than
public does
 However, protected visibility is not as tightly encapsulated as
private visibility
 Note: Unlike C++, Inheritance does not change the
visibility of the parent class members when used
through instances of child classes.
5
Transparency No. 1-56
Basic Java Syntax
Visibility modifiers and their usage
The visibility modifiers determine which class members can be
referenced from where and which cannot.
 public members:
 all classes
 protected members
 all classes in the same package +
 all subclasses (and subsubclasses …)
 Note: Java has no notions of public, private or protected inheritance as
in C++; all inheritances are public.
 package members [default visibility]
 all classes in the same package
 private members
 can only be used in the same class where the member is defined.
Transparency No. 1-57
Basic Java Syntax
Visible regions for members of class A
visible region for pubic members [of class A]
visible region for protected members
visible region for package members
package a.b.c
package a.b.c
… extend A
package a.b.c;
public class A {
public int p1…
protected int p2…
int p4; //package scope
private int p3 …
}
… extend A
… extend A
… extend A
visible region for
private members
of class A
Transparency No. 1-58
Basic Java Syntax
Protected members are accessible to subclass (and package) code
public class A {
public int p1;
protected int p2;
int p3
private int p4;
…}
public class B extends A{
…
// p1 and p2 of A can
// be used
}
class C extend B {
int p;
B b = new B();
…
p = b.p1; // ok since p1 is public
p = b.p2 ; // ok
p = p2; // ok ! protected p2 is inherited
A a = new A();
p = a.p2 // error!!
// protected field (p2) can be accessed
[from subclasses] only through
subclass instances
}
class D { B b = new B();
int i = b.p2;
//error p2 is not visible within D class
}
Transparency No. 1-59
Basic Java Syntax
The super Reference
 Constructors are not inherited, even though they are
declared to have public visibility
 Yet we often want to use the parent's constructor to set
up the "parent's part" of the object
 The super reference can be used to refer to the parent
class, and is often used to invoke the parent's
constructor
6
Transparency No. 1-60
Basic Java Syntax
class Book {
protected int pages;
public Book (int pages) { this.pages = pages; }
public void pageMessage () {
System.out.println ("Number of pages: " + pages); }
} // class Book
class Dictionary extends Book {
private int definitions;
public Dictionary (int pages, int definitions) {
super (pages); // construct Book part of a Dictionary
this.definitions = definitions;
} // constructor Dictionary
public void definitionMessage () {
System.out.println ("Number of definitions: " + definitions);
System.out.println ("Definitions per page: " + definitions/pages);
} // method definitionMessage
} // class Dictionary
Transparency No. 1-61
Basic Java Syntax
class Main2 {
public static void main (String[] args) {
Dictionary webster = new Dictionary (1500, 52500);
webster.pageMessage();
webster.definitionMessage();
System.out.println(webster); // try println object
} // method main
} // class Words2
Transparency No. 1-62
Basic Java Syntax
Single vs. Multiple Inheritance
 Java supports single inheritance, meaning that a
child class can have only one parent class
 Multiple inheritance allows a class to be derived
from two or more classes, inheriting the members of
all parents
 Collisions, such as the same variable name in two
parents, have to be resolved
 In most cases, the use of interfaces gives us the
best aspects of multiple inheritance without the
overhead
Transparency No. 1-63
Basic Java Syntax
Types of Objects and Variables
 The type of an object is the class that is referred to when it is
created via new construct.
 Student s1 = new Student(“name”, age, sex);
 Two types associated with variables ( including method
parameters/fields):
 The declared type of a variable is the type referred to in its declaration
(also: declared class; compile-time type)
 Person p1, p2 = new Person(…) ;
 The actual type of a variable is the type of the object bound to the
variable at a specific moment during program execution (also: runtime type)
 p1 = s1 ;
 Note: the declared type of a variable is static(i.e., unchangable ) once
it is declared, while the actual type of a variable is dynamic (i.e., can
be changed by assignment of new object of different type.
 p2 = s1;
Transparency No. 1-64
Basic Java Syntax
Example: Declared type and actual type
Transparency No. 1-65
Basic Java Syntax
Example Actual type
Transparency No. 1-66
Basic Java Syntax
Overriding Methods
 What happens if both parent and child class
contains members of the same signature ?
 fields => variable shadowing; constructor : impossible!
 methods => methods overriding
 A child class can override the definition of an
inherited method in favor of its own
 A child can redefine a method it inherits from its parent
 Overriding method:
 has the same signature as the parent's method
 has different code in the body
 The actual type (not casted type) of an object
determines which method is invoked
 See Messages.java
8
Transparency No. 1-67
Basic Java Syntax
class Messages {
public static void main (String[] args) {
Message m = new Message();
Advice a = new Advice();
m.message();
a.message();
(Message a).message() // same as a.message()
} } // class Messages
class Message {
public void message() {
System.out.println (”Message");
} } // class Thought
class Advice extends Message {
public void message() { // overriding method
System.out.println (”Advice");
} } // class Advice
Transparency No. 1-68
Basic Java Syntax
Overloading vs. Overriding
 Don‘t confuse the concepts of overloading (多載) and
overriding(覆蓋)
 Overloading deals with multiple methods in the same class
with the same name but different signatures
 Overriding deals with two methods, one in a parent class and
one in a child class, that have the same signature
 Overloading lets you define a similar operation in different
ways for different data
 Overriding lets you define a similar operation in different ways
for different object types
9
Transparency No. 1-69
Basic Java Syntax
The super Reference Revisited
 Inherited parent methods/fields can be explicitly
invoked using the super reference
 If a method/field is declared with the final modifier,
it cannot be overridden
 The concept of overriding can be applied to data
(called shadowing variables), but shadowing
behaves quite differently from overriding.
 The syntax of super is:
super.method (parameters)
super.var
 See Firm.java
10
Transparency No. 1-70
Basic Java Syntax
Shadowing superclass fields vs overriding superclass methods
class A { int x ; int m() …}
class B extends A { int x; int m() …}
class C extends B {
int x; // x in B and A are shadowed
// by this.x
int m() {…} // m() overrides m() in A & B
C c = new C(); …
x, this.x
// field x in C
super.x, ((B) this).x // field x in B
((A) this).x
// filed x in A
super.super.x // syntax error!!
c.x
// field in C
((B)c).x
// fields in B
((A)c).x
// fields in A
((A) c).m() ;
super.m();
((B) this).m();
((A) this).m();
((A) c).m();
((B) c).m();
m();
// m() in A ? no !!
// m() in B
// m() in C
// m() in C
// m() in C
Transparency No. 1-71
Basic Java Syntax
class Firm {
public static void main (String[] args) {
Manager sam = new Manager ("Sam", "123 Main Line",
"555-0469", "123-45-6789", 1923.07);
Employee carla = new Employee ("Carla", "456 Off Line",
"555-0101", "987-65-4321", 846.15);
Employee woody = new Employee ("Woody",
"789 Off Rocker", "555-0000", "010-20-3040", 769.23);
woody.print(); System.out.println ("Paid: " + woody.pay());
System.out.println();
carla.print(); System.out.println ("Paid: " + carla.pay());
System.out.println();
sam.print(); sam.awardBonus (2000);
System.out.println ("Paid: " + sam.pay());
System.out.println(); } }
Transparency No. 1-72
Basic Java Syntax
class Employee {
protected String name, address, phone, ID;
protected double salary;
public Employee (String name, String address,
String phone, String ID, double salary) {
this.name = name; this.address = address;
this.phone = phone; this.payRate = payRate; this.ID = ID;
} // constructor Employee
public double pay () { return salary; } // method pay
public void print () {
System.out.println (name + " " + ID);
System.out.println (address);
System.out.println (phone);
} } // class Employee
Transparency No. 1-73
Basic Java Syntax
class Manager extends Employee {
private double bonus;
public Manager (String name, String address, String phone,
String ID, double pay) {
super (name, nddress, phone, ID, pay); // call parent’s constructor
bonus = 0; // bonus yet to be awarded
}
public void awardBonus (double bonus) { this.bonus = bonus; }
public double pay () { // managers need special way to count pay!
double pay = super.pay() + bonus; // call parent’s method
bonus = 0;
return pay;
} }
Transparency No. 1-74
Basic Java Syntax
Class Hierarchies
 A child class of one parent can be the parent of
another child, forming class hierarchies
Animal
Mammal
Horse
Bird
Bat
Parrot
75
Transparency No. 1-75
Basic Java Syntax
Class Hierarchies
 Two children of the same parent are called
siblings
 Good class design puts all common features
as high in the hierarchy as is reasonable
 Class hierarchies often have to be extended
and modified to keep up with changing needs
 There is no single class hierarchy that is
appropriate for all situations
 See Accounts2.java
12
Transparency No. 1-76
Basic Java Syntax
class Accounts2 {
public static void main (String[] args) {
SavingsAccount savings =
new SavingsAccount (4321, 5028.45, 0.02);
BonusSaverAccount bigSavings =
new BonusSaverAccount (6543, 1475.85, 0.02);
CheckingAccount checking =
new CheckingAccount (9876, 269.93, savings);
savings.deposit (148.04);
bigSavings.deposit (41.52);
savings.withdrawal (725.55);
bigSavings.withdrawal (120.38);
checking.withdrawal (320.18);
} // method main
} // class Accounts2
Transparency No. 1-77
Basic Java Syntax
class BankAccount {
protected int account; protected double balance;
public BankAccount (int accountNum, double initialBalance) {
account = accountNum; balance = initialBalance; }
public void deposit (double amount)
{ balance += amount; } // method deposit
public boolean withdrawal (double amount) {
boolean result = false;
if (amount > balance)
System.out.println ("Insufficient funds.");
else { balance -= amount;
System.out.println ("New balance: " + balance);
result = true; }
return result; } } // class BankAccount
Transparency No. 1-78
Basic Java Syntax
class SavingsAccount extends BankAccount {
protected double rate;
public SavingsAccount (int accountNum,
double initialBalance, double interestRate) {
super (accountNum, initialBalance);
rate = interestRate;
} // constructor SavingsAccount
public void addInterest () {
balance += balance * rate;
} // method addInterest
} // class SavingsAccount
Transparency No. 1-79
Basic Java Syntax
class BonusSaverAccount extends SavingsAccount {
private final int PENALTY = 25;
private final double BONUSRATE = 0.03;
public BonusSaverAccount (int accountNum,
double initialBalance, double interestRate) {
super (accountNum, initialBalance, interestRate);
} // constructor SuperSaverAccount
public boolean withdrawal (double amount) {
return super.withdrawal (amount+PENALTY);
} // method withdrawal
public void addInterest () {
balance += balance * (rate + BONUSRATE);
} // method addInterest
Transparency No. 1-80
Basic Java Syntax
class CheckingAccount extends BankAccount {
private SavingsAccount overdraft;
public CheckingAccount (int accountNum,
double initialBalance, SavingsAccount protection) {
super (accountNum, initialBalance);
overdraft = protection; } // constructor CheckingAccount
public boolean withdrawal (double amount) {
boolean result = false;
if ( ! super.withdrawal (amount) ) {
System.out.println ("Using overdraft...");
if ( ! overdraft.withdrawal (amount - balance) )
System.out.println ("Overdraft source insufficient.");
else { balance = 0;
System.out.println ("New balance on account " +
account + ": " + balance);
result = true;
}
}
return result; }
} // class CheckingAccount
Transparency No. 1-81
Basic Java Syntax
The Object Class
 A class called Object is defined in the java.lang
package of the Java standard class library
 All objects are derived from the Object class
 If a class is not explicitly defined to be the child of an
existing class, it is assumed to be the child of the
Object class
 The Object class is therefore the ultimate root of all
class hierarchies
 The Object class contains a few useful methods, such
as toString(),equals(), hashCode() which are inherited
by all classes
 You may choose to override equals and/or
toString to define equality/toString in your way.13
Transparency No. 1-82
Basic Java Syntax
import java.awt.Point;
class TestToString {
public static void main (String[] args) {
Integer n = new Integer (25);
Point p = new Point (0, 0);
A
a = new A();
System.out.println ( n.toString() );
System.out.println ( p.toString() );
System.out.println ( a.toString() );
} // method main
} // class TestToString
class A {
public String toString() { return "I am AnyClass"; } // method toString
} // class AnyClass
Transparency No. 1-83
Basic Java Syntax
Abstract Classes revisted
 An abstract class is a placeholder in a class
hierarchy that represents a generic concept
 An abstract class cannot be instantiated
 We use the modifier abstract on the class header
to declare a class as abstract
 An abstract class often contains abstract methods
(like an interface does), though it doesn’t have to
Transparency No. 1-84
Basic Java Syntax
Abstract Classes
 The child of an abstract class must override the
abstract methods of the parent, or it too will be
considered abstract
 An abstract method cannot be defined as final
(because it must be overridden) or static (because it
has no definition yet)
 The use of abstract classes is a design decision; it
helps us establish common elements in a class that
is too general to instantiate
Transparency No. 1-85
Basic Java Syntax
References and Inheritance
 An object reference can refer to an object of its
class, or to an object of any class related to it by
inheritance
 For example, if the Holiday class is used to derive
a child class called Christmas, then a Holiday
reference could actually be used to point to a
Christmas object
Holiday
Holiday day;
day = new Christmas();
Christmas
86
Transparency No. 1-86
Basic Java Syntax
References and Inheritance
 Assigning a descendant class instance to an
ancestor reference is considered to be a widening
conversion, and can be performed by simple
assignment
 Assigning an ancestor object to a subclass
reference can also be done, but it is considered to
be a narrowing conversion and must be done with a
cast
 The widening conversion is the most useful
87
Transparency No. 1-87
Basic Java Syntax
Polymorphism
 A polymorphic reference is one which can refer to one
of several possible methods.
 Same invocation expression(say o.m(…)), different methods
actually called.
 Suppose the Holiday class has a method called
celebrate, and the Christmas class overrode it
 Now consider the following invocation:
day.celebrate();
 If day refers to a Holiday object, it invokes Holiday's
version of celebrate; if it refers to a Christmas object, it
invokes that version
16
Transparency No. 1-88
Basic Java Syntax
Polymorphism
 In general, it is the type of the object being referenced,
not the reference type, that determines which method is
invoked
 Note that, if an invocation is in a loop, the exact same
line of code could execute different methods at different
times
 Polymorphic references are therefore resolved at runtime, not during compilation
17
Transparency No. 1-89
Basic Java Syntax
Polymorphism
 Note that, because all classes inherit from the Object
class, an Object reference can refer to any type of
object
 A Vector is designed to store Object references
 The instanceOf operator can be used to determine the
class from which an object was created
 See Variety.java
18
Transparency No. 1-90
Basic Java Syntax
import java.awt.Point; import java.util.Vector;
class MyVariety {
public static void main (String[] args) {
Vector collector = new Vector();
Integer num1 = new Integer (10); collector.addElement (num1);
Point origin = new Point (0, 0); collector.addElement (origin);
Integer num2 = new Integer (37);collector.addElement (num2);
Point corner=new Point (12, 45);collector.addElement (corner);
int temp; Object something;
for (int count=0; count < collector.size(); count++) {
something = collector.elementAt (count);
if (something instanceof Integer) {
temp = ((Integer)something).intValue() + 20;
System.out.println (something + " + 20 = " + temp); }
else System.out.println ("Point: " + something);
}
}}
Transparency No. 1-91
Basic Java Syntax
Polymorphism via Inheritance
 Consider the following class hierarchy:
StaffMember
Volunteer
Employee
Executive
Hourly
Transparency No. 1-92
Basic Java Syntax
class Firm2 {
public static void main (String[] args) {
Staff personnel = new Staff();
personnel.payday();
}
}
Transparency No. 1-93
class Staff {
StaffMember[] staffList = new StaffMember[6];
public Staff() {
Basic Java Syntax
staffList[0] = new Executive ("Sam", "123 Main Line", "555-0469",
"123-45-6789", 1923.07);
staffList[1] = new Employee ("Carla", "456 Off Line",
"555-0101", "987-65-4321", 846.15);
staffList[2] = new Employee ("Woody", "789 Off Rocker",
"555-0000", "010-20-3040", 769.23);
staffList[3] = new Hourly ("Diane", "678 Fifth Ave.",
"555-0690", "958-47-3625", 8.55);
staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.", "555-8374");
staffList[5] = new Volunteer ("Cliff", "321 Duds Lane", "555-7282");
((Executive)staffList[0]).awardBonus (5000);
((Hourly)staffList[3]).addHours (40);
} // constructor Staff
Transparency No. 1-94
Basic Java Syntax
public void payday() {
double amount;
for (int count=0; count < staffList.length; count++) {
staffList[count].print();
amount = staffList[count].pay();
if (amount == 0.0)
System.out.println ("Thanks!");
else System.out.println ("Paid: " + amount);
System.out.println ("**********************");
}
} // method payday
} // class Staff
Transparency No. 1-95
Basic Java Syntax
class StaffMember {
protected String name, address, phone;
public StaffMember (String empName, String empAddress,
String empPhone) {
name
= empName;
address = empAddress;
phone
= empPhone;
} // constructor StaffMember
public double pay() { return 0.0; } // default pay method
public void print() {
System.out.println ("Name: " + name);
System.out.println ("Address: " + address);
System.out.println ("Phone: " + phone);
} } // class StaffMember
Transparency No. 1-96
Basic Java Syntax
class Volunteer extends StaffMember {
public Volunteer (String empName, String empAddress,
String empPhone) {
super (empName, empAddress, empPhone);
} // constructor Volunteer
public double pay() {
return 0.0;
} // method pay
} // class Volunteer
Transparency No. 1-97
Basic Java Syntax
class Employee extends StaffMember {
protected String ID; protected double payRate;
public Employee (String empName, String empAddress,
String empPhone, String empSsnumber, double empRate) {
super (empName, empAddress, empPhone);
this.ID = ID; payRate = empRate;
} // constructor Employee
public double pay () { return payRate; } // method pay
public void print () {
super.print();
System.out.println (“ID number: " + ID);
System.out.println ("Pay rate: " + payRate);
} // method print
} // class Employee
Transparency No. 1-98
Basic Java Syntax
class Executive extends Employee {
private double bonus;
public Executive (String name, String addr, String phone,
String ID, double pay) {
super (name, addr, phone, ID, pay);
bonus = 0; // bonus yet to be awarded
} // constructor Executive
public void awardBonus (double bonus) {
this.bonus = bonus; } // method awardBonus
public double pay () {
double pay = super.pay() + bonus;
bonus = 0;
return pay; } // method pay
public void print () {
super.print();
System.out.println ("Current bonus: " + bonus);
} // method print
}
Transparency No. 1-99
Basic Java Syntax
class Hourly extends Employee {
private int hoursWorked;
public Hourly (String name, String addr,
String phone, String ID, double hrRate) {
super (name, address, phone, ID, hrRate);
hoursWorked = 0; }
public void addHours (int moreHours) {
hoursWorked += moreHours;
} // method addHours
public double pay () {
return payRate * hoursWorked;
} // method pay
public void print () {
super.print();
System.out.println ("Current hours: " + hoursWorked);
} // method print
} // class Hourly
Transparency No. 1-100
Basic Java Syntax
Summary for inheritance
• Inheritance: reuse the existing objects (is-a relation)
• Protect modifier: better encapsulation
• Use super to invoke parent’s methods.
• Overriding methods and overloaded methods
• All Java classes inherit from object class
• Polymorphism: which overriding method is invoked
based on the object’s type
• Widening & narrowing
Transparency No. 1-101
Basic Java Syntax
Interfaces
 A Java interface is a collection of abstract methods and
constants
 An abstract method is a method header without a
method body (i.e., no implementation)
 An abstract method in an interface can be declared
using the modifier abstract, but because all
methods in an interface are abstract, it is usually left off.
 cf: abstract methods in an abstract class must be declared
explicitly using the abstract modifier.
 An interface is used to formally define a set of methods
that a class will implement
Transparency No. 1-102
Basic Java Syntax
Interfaces
interface is a reserved word
None of the methods in an
interface are given
a definition (body)
public interface Doable
{
public void doThis();
public int doThat();
public void doThis2 (float value, char ch);
public boolean doTheOther (int num);
}
A semicolon immediately
follows each method header
Transparency No. 1-103
Basic Java Syntax
Interfaces
 An interface cannot be instantiated
 Doable d = new Doable(); // error
 Like a class, a user-defined interface can be used as the type
of variables.
 Doable a, b;
 Methods in an interface have public visibility by default
 A class formally implements an interface by
 stating so in the class header
 providing implementations for each abstract method in the interface
 If a class asserts that it implements an interface, it must
define all methods in the interface or the compiler will
produce errors.
Transparency No. 1-104
Basic Java Syntax
Interfaces
public class CanDo implements Doable
{
implements is a
public void doThis ()
{
reserved word
// whatever
}
public void doThat ()
{
// whatever
}
Each method listed
in Doable is
given a definition
// etc.
}
Transparency No. 1-105
Basic Java Syntax
Interfaces
 A class can implement more than one interfaces
 See Speaker.java (page 236)
 See Philosopher.java (page 237)
 See Dog.java (page 238)
 The interfaces are listed in the implements clause,
separated by commas
 The class must implement all methods in all
interfaces listed in the header
Transparency No. 1-106
Basic Java Syntax
Interfaces
 An interface can be implemented by multiple
classes
 Each implementing class can provide their own
unique version of the method definitions
 An interface is not part of the class hierarchy
 A class can be derived from a base class and
implement one or more interfaces
9
Transparency No. 1-107
Basic Java Syntax
Interface constants
 Unlike interface methods, interface constants
require nothing special of the implementing class
 Constants in an interface can be used in the
implementing class as if they were declared locally
 This feature provides a convenient technique for
distributing common constant values among
multiple classes
10
Transparency No. 1-108
Basic Java Syntax
Extending Interfaces
 An interface can be derived from another interface,
using the extends reserved word
 The child interface inherits the constants and
abstract methods of the parent
 Note that the interface hierarchy and the class
hierarchy are distinct
 Unlike class hierarchy, an interface can extend more
than one interfaces.
 public interface Transformable extends Scable,
Translatable, Rotatable { }
 A class that implements an interface must define
also all methods in all ancestors of the interface.
11
Transparency No. 1-109
Basic Java Syntax
An interface Example
interface Printable {
public String name();
public String print(); // public can be omitted
} // interface Printable
class PrintLogger {
public void log (Printable file) {
System.out.println (file.name() + " : " + file.print());
} // method log
} // class PrintLogger
Transparency No. 1-110
Basic Java Syntax
class File {
protected String id; protected int size;
public File (String id, int size) {
this.id = id; this.size = size;
} // constructor File
public String name() { return id; } // method name
} // class File
class TextFile extends File implements Printable {
protected String text;
public TextFile (String id, int size, String contents) {
super(id, size); text = contents;
} // constructor TextFile
public String print() { return text; }
} // class TextFile
Transparency No. 1-111
Basic Java Syntax
class BinaryFile extends File {
protected byte[] data;
public BinaryFile (String id, int size, byte[] data) {
super(id, size); this.data = data;
} // constructor BinaryFile
} // class BinaryFile
class ImageFile extends BinaryFile implements Printable {
public ImageFile (String id, int size, byte[] data) {
super(id, size, data);
} // constructor ImageFile
public String print() { return new String (data); }
} // class Image_File
Transparency No. 1-112
Basic Java Syntax
public class Printer {
public static void main (String[] args) {
byte[] logoData = {41, 42, 49, 44 };
TextFile report = new TextFile
(“Reprot 1", 1024, "One two three …");
ImageFile logo = new ImageFile(“Picture 1", 4, logoData);
PrintLogger daily = new PrintLogger();
daily.log (report);
daily.log (logo);
}
}
Transparency No. 1-113
Basic Java Syntax
Marker interface
 An interface without including any method.





useful for providing additional information about an object.
EX:
java.lang.Serializable
java.lang.Cloneable
java.rmi.Remote
Ex:
Object obj;
Object copy;
copy = o.clone() // may raise CloneNotSupportedExceptionexception
if(obj instanceof Cloneable) copy = o.clone();
else copy = null;
Transparency No. 1-114
Basic Java Syntax
Polymorphism via Interfaces
 An interface name can be used as the type of an
object reference variable
Doable obj;
 The obj reference can be used to point to any
object of any class that implements the Doable
interface
 The version of doThis that the following line
invokes depends on the type of object that obj is
referring to:
obj.doThis();
Transparency No. 1-115
Basic Java Syntax
Polymorphism via Interfaces
 That reference is polymorphic, which can be defined
as "having many forms"
 That line of code might execute different methods at
different times if the object that obj points to
changes
 See PrinterLogger.java(slide 106)
 Note that polymorphic references must be resolved
at run time; this is called dynamic binding
 Careful use of polymorphic references can lead to
elegant, robust software designs
Transparency No. 1-116
Basic Java Syntax
Some interfaces used in core java classes
 The Java standard class library contains many interfaces that
are helpful in certain situations
 The Comparable interface contains an abstract method called
compareTo, which is used to compare two objects
pubilc iterface Comparable {
public abstract int comparedTo(Object); }
Ex: int rlt = x.comparedTo(y);
if(rlt < 0) {… } // x < y
else if (rlt>0) { …} // x > y
else {…} // rlt = 0 means x is equal to y.
 The String class implements Comparable which gives us the
ability to put strings in alphabetical order
Transparency No. 1-117
Basic Java Syntax
The Iterator and Enumeration interface
The java.util.Iterator/Enumeration interface contain methods that
allow the user to move through a collection of objects easily
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
public abstract void remove(); }
pubic interface Enumeration {
public boolean hasMoreElements();
pubic Object nextElement(); }
Ex: Object obj ; // obj is an object implementing Iterator
for(Iterator i = (Iterator)obj; i.hasNext(); )
processing(i.next());
Transparency No. 1-118
Basic Java Syntax
Events [skipped]
 An event is an object that represents some activity
to which we may want to respond
 For example, we may want our program to perform
some action when the following occurs:






the mouse is moved
a mouse button is clicked
the mouse is dragged
a graphical button is clicked
a keyboard key is pressed
a timer expires
 Often events correspond to user actions, but not
always
Transparency No. 1-119
Basic Java Syntax
Events
 The Java standard class library contains several
classes that represent typical events
 Certain objects, such as an applet or a graphical
button, generate (fire) an event when it occurs
 Other objects, called listeners, respond to events
 We can write listener objects to do whatever we
want when an event occurs
Transparency No. 1-120
Basic Java Syntax
Events and Listeners
Event
Source
Listener
This object may
generate an event
This object waits for and
responds to an event
When an event occurs, the source calls
the appropriate method of the listener,
passing an Event object that describes the event
Transparency No. 1-121
Basic Java Syntax
Listener Interfaces
 We can create a listener object by writing a class
that implements a particular listener interface
 The Java standard class library contains several
interfaces that correspond to particular event
categories
 For example, the MouseListener interface contains
methods that correspond to mouse events
 After creating the listener, we add the listener to the
component that might generate the event to set up a
formal relationship between the generator and
listener
Transparency No. 1-122
Basic Java Syntax
Mouse Events
 The following are mouse events:




mouse pressed - the mouse button is pressed down
mouse released - the mouse button is released
mouse clicked - the mouse button is pressed and released
mouse entered - the mouse pointer is moved over a
particular component
 mouse exited - the mouse pointer is moved off of a
particular component
 Any given program can listen for some, none, or all
of these
 See Dots.java (page 246)
 See DotsMouseListener.java (page 248)
Transparency No. 1-123
Basic Java Syntax
Mouse Motion Events
 The following are called mouse motion events:
 mouse moved - the mouse is moved
 mouse dragged - the mouse is moved while the mouse
button is held down
 There is a corresponding MouseMotionListener
interface
 One class can serve as both a generator and a
listener
 One class can serve as a listener for multiple event
types
 See RubberLines.java (page 249)
Transparency No. 1-124
Basic Java Syntax
Key Events
 The following are called key events:
 key pressed - a keyboard key is pressed down
 key released - a keyboard key is released
 key typed - a keyboard key is pressed and released
 The KeyListener interface handles key events
 Listener classes are often implemented as inner
classes, nested within the component that they are
listening to
 See Direction.java (page 253)
Transparency No. 1-125
Basic Java Syntax
Animations
 An animation is a constantly changing series of
pictures or images that create the illusion of
movement
 We can create animations in Java by changing a
picture slightly over time
 The speed of a Java animation is usually controlled
by a Timer object
 The Timer class is defined in the javax.swing
package
Transparency No. 1-126
Basic Java Syntax
Animations
 A Timer object generates an ActionEvent every n
milliseconds (where n is set by the object creator)
 The ActionListener interface contains an
actionPerformed method
 Whenever the timer expires (generating an
ActionEvent) the animation can be updated
 See Rebound.java (page 258)
Transparency No. 1-127
Basic Java Syntax
Summary of Java Modifiers
 Modifiers used in java:









for accessibility: public, [package], protected, private
abstract,
final,
static
native,
strictfp
synchronized
transient
volatile
Transparency No. 1-128
Basic Java Syntax
usage of accessibility modifiers
modifier
private
used on
accessible to code from
member (i.e. field, the containing class
constructor or
method)
none[package]
class, interface,
member
the containing package
protected
member
the containing package
or subclasses of the
containing class
public
class, interface,
member
anywhere
Transparency No. 1-129
Basic Java Syntax
usage of abstract, final and static modifiers
modifier
used on
Meaning
abstract
class +
interface
contains abstract
methods
the body is not
implemented
final
static
method
class
cannot be extended
method
cannot be overridden
field + variable cannot be changed
class+interface the nested class
(interface) is top-level
class field(method)
field+method
run when class loaded
initializer
Transparency No. 1-130
Basic Java Syntax
usage of native, synchronized, transient, strictfp and volatile
modifier
used on
meaning
native
method
implemented by nonjava code. no method
body.
synchronized
method
lock this.class or this
before executing
method
transient
field
non-persistent data;
need not be serialized
volatile
(rarely used)
field
updated value on thread
WM must be reflected
on MM immediately.
strictfp
(rarely used)
method
FP operations must
strictly conform to
IEEE754
Transparency No. 1-131
Basic Java Syntax
Example of transient fields
class Point {
int x, y;
transient float rho, theta;
} // rho and theta are not persistent data
Transparency No. 1-132
Basic Java Syntax
Example of synchronized method and volatile field
class Test {
static int i = 0, j = 0;
static void one() { i++; j++; }
static void two() { System.out.println("i=" + i + " j=" + j);
}}
 Volatile modifier guarantees that any thread that read a field will
get the most recently written value.
Transparency No. 1-133
Basic Java Syntax
Example of synchronized method and volatile field
public class Main {
pubic static void main(String[] args){
new Thread1().start();
new Thread2().start();
}}
class Thread1 extend Thread {
public void run(){ for(;;) Test.one();} }
class Thread2 extend Thread {
public void run(){ for(;;) {Test.two(); sleep(500); } }
// it is possible that Thread2 prints a result with
// j > i, since i,j may be updated out of order in MM.
Transparency No. 1-134
Example of synchronized method and volatile field
Basic Java Syntax
class Test {
static int i = 0, j = 0;
static synchronized void one() { i++; j++; }
static synchronized void two() {
System.out.println("i=" + i + " j=" + j);
} } // i and j must be equal
class Test {
static volatile int i = 0, j = 0;
static void one() { i++; j++; }
static void two() {
System.out.println("i=" + i + " j=" + j);
} } // i always >= j.
Transparency No. 1-135
Basic Java Syntax
Nested Classes
 In addition to a class containing data and methods,
it can also contain other classes
 A class declared within another class is called a
nested class (or called inner class)
Outer Class
Nested
Class
Transparency No. 1-136
Basic Java Syntax
Why Nested Classes
 A nested class has access to the variables and
methods of the outer class, even if they are declared
private
 Nested classes can be hidden from other classes in
the same package.
 Anonymous classes are handy when defining
callbacks on the fly.
 Convenient when writing event-driven programming
Transparency No. 1-137
Basic Java Syntax
Nested Classes
 A nested class produces a separate bytecode file
 If a nested class called Inside is declared in an outer
class called Outside, two bytecode files will be
produced:
Outside.class
Outside$Inside.class
 Nested classes can be declared as static, in which
case they cannot refer to this, instance variables or
methods of outer classes.
 A nonstatic nested class is called an inner class
Transparency No. 1-138
Basic Java Syntax
Kinds of Java classes /interfaces
Top-level classes /interfaces
 Non-nested top-level classes/interfaces
 are ordinary classes/interfaces that are direct members of a package.
 Nested top-level classes / interfaces
 are static members of other top-level classes/interfaces
 nested interfaces are implicitly static (hence top-level).
Inner classes:
 Member classes
 are non-static nested classes
 Local classes
 are classes defined inside method body
 Anonymous classes
 are classes defined within method body without given a class name
Transparency No. 1-139
Basic Java Syntax
Example
class A { …
static A1 { // I am a nested top-level class
…}
A2 { // w/o static modifier, so I am a member class
…}
void m1(…) {
class A3 { // A3 is declared inside a method, so is a
local class …}
…}
void m2(…) { // A4 is an interface or class
A4 a = new A4() { void m3() {…} m4() … };
// a is an object of an anonymous
subclass/implementation of A4.
Transparency No. 1-140
Basic Java Syntax
Nested top-level classes /interfaces
 also called static member classes/interfaces
 behave like an ordinary top-level class/interface
except that
 it can access the static members of all of its direct or
indirect containing classes.
 can be public, protected, package or private.
 Should use the name A.B.C t o reference to a class C
enclosed by class B enclosed by class A.
A
B
A
B
C
Transparency No. 1-141
Basic Java Syntax
Example of a static member interface
public class LinkedStack {
public interface Linkable { // interfaces are static by default.
public Linkable getNext();
top
Linkable
getNext()
public void setNext(Linkable node); }
Linkable
// The top of the stack is a Linkable object.
Linkable
Linkable top;
public LinkedStack() {};
Linkable
pubic boolean empty() { return (top == null) ;} null
public void push(Linkable node) { node.setNext(top); top = node; }
public Object pop(Linkable node) throw EmptyStackException {
if(empty()) throw new EmptyStackException();
Object r = top; top = top.getNext(); return r; } }
Transparency No. 1-142
Basic Java Syntax
// This class defines a type of node that we'd like to
// use in a linkedStack.
class IntegerNode implements LinkedStack.Linkable
{
// Here's the node's data and constructor.
private int i;
public IntegerNode(int i) { this.i = i; }
// implementation of LinkedStack.Linkable.
private LinkedList.Linkable next;
public LinkedList.Linkable getNext() { return next; }
public void setNext(LinkedList.Linkable node)
{ next = node; }
}
Transparency No. 1-143
Basic Java Syntax
public class test {
pubic static void main(String[] args) {
// declare an array of 10 IntergerNodes
IntergerNode[] n = new IntergerNode[10];
LinkedStack s = null;
for (int i = 0; i < n.length; i++) {
n[i] = new IntergerNode(i);
s.push(n[i]) ;
}
while(! s.empty()) System.out.println(s.pop());
}
Transparency No. 1-144
Basic Java Syntax
Features of static member classes
 obey the same rules of static methods:
 can access only static members (using simple or full name)
 accessible to other classes according to the used visibility
modifier.
 note: useful for compiler only.
 as to interpreters:
 pubic or protected nested/member classes

=> visible to all classes,
 package or private nested/member classes

=> visible to containing package
Transparency No. 1-145
Basic Java Syntax
 How to reference a nested static class C inside
[static] class A of [static] class B of package a.b :






outside package a.b => a.b.A.B.C
if import a.b.A.B.C or a.b.A.B.* => C // not recommended
if import a.b.A.B or a.b.A.* => B.C // not recommended
inside package a.b => A.B.C (or a.b.A.B.C)
inside class A => B.C (or A.B.C or a.b.A.B.C)
inside class B => C ( or any of the above)
 Note: All static fields, methods, and classes of a top
level class are accessible to all code [even inside a
static class] within the class no matter they are
private or not.
Transparency No. 1-146
Basic Java Syntax
import LinkedStack.Linkable;
// or import LinkedStack.*;
class IntegerNode implements Linkable
{
// Here's the node's data and constructor.
private int i;
public IntegerNode(int i) { this.i = i; }
// implementation of LinkedStack.Linkable.
private LinkedList.Linkable next;
public Linkable getNext() { return next; }
public void setNext(Linkable node)
{ next = node; }
}
Transparency No. 1-147
Basic Java Syntax
access references in nested classes
public class A { static int a; static private int ma();
static class B1 { static int y1; static private int mb1();
static class C1 { static int c1; static int mc1(); }}
static class B2 {
static class B1 { … }
static int b2; static private int mb2();
static class C2 { // various ways to access other members
// a, A.a, ma(), A.ma(), B1, A.B1 reference A’s members
// b2, B2.b2, A.B2.b2, mb2, B2.mb2(), A.B2.mb2(), B2.B1, B1.
// A.B1.y1, A.B1.C1.c1, B1.C1.c1, C1.c1
}}
Transparency No. 1-148
Basic Java Syntax
Member classes
 static class behaves like static fields/methods
 member class  behaves like instance fields/methods
 beside referring to all static fields/methods, can also reference this,
instance field/method of all enclosing classes, even they are private.
 associated with an instance of each of the enclosing classes
 Member class v.s. Static class
 static class and its enclosing classes are static class-class relationship
 member class and its enclosing classes are instance-instance
relationship.
 1. Each member class instance must be created/accessed through
instances of the containing class.
 2. Each member class instance is associated with an unique instance
of each of its containing classes.
Transparency No. 1-149
Basic Java Syntax
Example: A LinkedList Enumerator, as a Member Class
import java.util.Enumeration;
public class LinkedStack { // those from old LinkedStack
public interface Linkable { ... }
private Linkable top;
public void push(…) { ... } public Object pop() { ... }
// This method returns an Enumeration object for this inkedStack.
// Note: no LinkedStack object is explicitly passed to the
//
constructor.
public Enumeration enumerate() { return new Enumerator(); }
Transparency No. 1-150
Basic Java Syntax
Example: A LinkedList Enumerator, as a Member Class
// the implementation of the Enumeration interface.
protected class Enumerator implements Enumeration {
Linkable current;
public Enumerator() { current = top; }
public boolean hasMoreElements() { return (current != null); }
public Object nextElement() {
if (current == null)
throw new NoSuchElementException("LinkedStack");
Object value = current;
current = current.getNext();
return value;
} }}
 Note: Enumerator is only accessible to subclasses
or the package of LinkedStack.
Transparency No. 1-151
Basic Java Syntax
Restrictions on member classes
 A member class cannot have the same name as any
containing class or package.
 Member classes cannot contain any static fields,
methods or classes (with the exception of constant
fields).
 since member class is associated with object instances, it
is nonsense/needless to have static members.
 Interfaces cannot be defined as member classes.
 since interfaces cannot be instantiated, there is no way for
an object to create an interface instance.
 A nested interface is by default static, even if the modifier
‘static’ is not given in the header.
Transparency No. 1-152
Basic Java Syntax
New syntax for member classes
 member class can access instance field/method of containing
class.
 public Enumerator() { current = top; }
 How to make the reference explicit ?
 public Enumeration() { this.current = this.top;}
 // this.current ok ; but this.top err!!
 // since there is no top in class Enumeration
 Solution:
 public Enumeration() { this.current = LinkedStack.this.top;}
 New syntax: C: a containing class name
 C.this is used to reference the associated C instance.
 needed only when using this incurs ambiguity.
Transparency No. 1-153
Basic Java Syntax
accessing superclass members of the containing class
 Recall that we use super.f (or super.m(…)) to reference
shadowed or overridden member of parent class of this.
 Likewise, we use
 C.super.f
 to reference the f field of the parent class of C, which is a
containing class of this, and use
 C.super.m()
 to reference the method m() of the parent class of C.
Transparency No. 1-154
using containing class instance to invoke constructors
of member class
Basic Java Syntax
 Every instance of a member class is associated with
an instance of its containing class.
 pubic Enumeration enumerate(){return new Enumeration();}
 can also be written as
 pubic Enumeration enumerate() { return this.new
Enumeration;}
 More useful case:




LinkedStack stack = new LinkedStack();
Enumeration e1 = stack.enumerate();
// could create one without invoking enumerate()!!
Enumeration e1 = stack.new Enumeration();
 syntax: C: a containing class of member class D
with constructor D(…); s : this or var of type C
 s.new D(…) will invoke D(…) of class D in instance of C
referenced by s.
Transparency No. 1-155
Basic Java Syntax
Some special case
 It is possible that a class extends a member class.




public class A { …
public class B { …} …}
class C extend A.B {
pubic C( … ) { ??? } … }
 problem: what is the instance of the containing
class A of the parent class B of C
 Solution:
 pubic C( A a, … ) { a.super(…); }
Transparency No. 1-156
Basic Java Syntax
Containing Hierarchy vs Inheritance Hierarchy
class A extends A1 { int x;
class B extends B1 { int x;
class C extends C1 { int x; …} } }
class A1 { int x; …}
class B1 { int x; …}
class C1 extends C2 { int x; …}
class C2 { int x; … }
Problem: how to reference different x in class C.




this.x, C.this.x // x in C
A.this.x // x in A
((C2)this).x // x in C2
((A1) (A.this)).x, A.super.x
B.this.x // x in B
super.x, ((C1)this).x // x in C1
((B1) (B.this)).x, B.super.x // x in B1
// x in A1
Problem: how about overridden methods ?
Transparency No. 1-157
Basic Java Syntax
Local Classes
 class declared locally within a block of Java code.
 within method body
 within instance/static initialization block
 Feature of Local class:
 Local class is to member class what local variable is to
instance variable.
 Properties similar to that of local variables:
 1. invisible outside the containing block.
 2. cannot use accessibility or static modifiers
 Properties similar to member classes
 1.can access any member of any containing classes.
 2. no local interfaces
 can use any final local variables or method parameters
that are visible from the scope in which they are defined.
Transparency No. 1-158
Basic Java Syntax
Example: Defining and using a Local Class
// This method creates and returns an Enumeration object for this LinkedStack.
public Enumeration enumerate() {
// Here's the definition of Enumerator as a local class.
class Enumerator implements Enumeration {
Linkable current;
public Enumerator() { current = top; }
public boolean hasMoreElements() { return (current != null); }
public Object nextElement() { … } // omitted
}
// Create and return an instance of the Enumerator class defined here.
return new Enumerator();
}
Transparency No. 1-159
Basic Java Syntax
Fields and variables accessible to a local class
class A { protected char a = 'a'; }
class B { protected char b = 'b'; }
pubic class C extends A {
public static void main(String[] args) {
// Create an instance of the containing class, and invoke the
// method that defines and creates the local class.
C c = new C();
c.createLocalObject('e'); // pass a value for final parameter e.
}
Transparency No. 1-160
Basic Java Syntax
private char c = 'c';
// Private fields visible to local class.
public static char d = 'd';
public void createLocalObject(final char e) {
final char f = 'f'; int i = 0; // i not final; not usable by local class.
class Local extends B { char g = 'g';
public void printVars() { // All of these fields and variables are accessible.
System.out.println(g); // (this.g) g is a field of this class.
System.out.println(f); // f is a final local variable.
System.out.println(e); // e is a final local argument.
System.out.println(d); // (C.this.d) d -- field of containing class.
System.out.println(c); // (C.this.c) c -- field of containing class.
System.out.println(b); // b is inherited by this class.
System.out.println(a); // a is inherited by the containing class. } }
Local l = this.new Local(); // Create an instance of the local class
l.printVars();
// and call its printVars() method.
}
Transparency No. 1-161
Basic Java Syntax
Typical uses of local classes [TBA]
 used to implement adapter classes
Transparency No. 1-162
Basic Java Syntax
Anonymous classes
 a local class without a name
 very commonly used as adapter classes.
 created through another extension to the syntax of
the new operator.
 defined by a Java expression, not a Java statement.
Transparency No. 1-163
Basic Java Syntax
Example: Implementing an Interface with an Anonymous Class
import java.io.*;
// A simple program to list all Java source files in a directory
public class Lister {
public static void main(String[] args) {
File dir = new File(args[0]); // f represents the specified directory.
// List the files in the directory, using the specified filter object.
// The anonymous class is defined as part of a method call expression.
String[] list = dir.list( new FilenameFilter() {
public boolean accept(File f, String name) {
return name.endsWith(".java");
}});
for(int i = 0; i < list.length; i++) // output the list
System.out.println(list[i]);
}}
Transparency No. 1-164
Basic Java Syntax
Anonymous class vs local class
 when to use anonymous class:




The class has a very short body.
Only one instance of the class is needed.
The class is used right after it is defined.
The name of the class does not make your code any easier
to understand.
 Restrictions on anonymous classes:
 An anonymous class has no name and hence cannot be
used to create more than one instance for each execution.
 It is not possible to define constructors for anonymous
classes.
Transparency No. 1-165
Basic Java Syntax
Example: Enumeration implemented as an anonymous class
public Enumeration enumerate() {
// Instantiate and return this implementation.
return new Enumeration() {
Linkable current = top; // This used to be in the constructor, but
// anonymous classes don't have constructors.
public boolean hasMoreElements() { return (current != null); }
public Object nextElement() {
if (current == null) throw new NoSuchElementException("LinkedList");
Object value = current;
current = current.getNext();
return value; }
}; // Note the required semicolon. It terminates the return statement.
}
Transparency No. 1-166
Basic Java Syntax
Additional Java Syntax for Anonymous Classes
 syntax:
 new class-name ( [ argument-list ] ) { class-body }
 new interface-name () { class-body }
 Syntax 1 return an instance of an anonymous subclass of classname
 the subclass can provide additional (helper ) methods/fields and/or
overrides or implements existing super class methods.
 Syntax 2 return an instance of a class implementing interfacename.
Transparency No. 1-167
Basic Java Syntax
use initializer to help construct anonymous class instances
public class InitializerDemo { public int[] array1;
// This is an instance initializer.
// It runs for every new instance, after the superclass constructor
// and before the class constructor, if any.
{ array1 = new int[10];
for(int i = 0; i < 10; i++) array1[i] = i; }
// another instance initializer. The instance initializers run in the order in
// which they appear.
int[] array2 = new int[10]; { for(int i=0; i<10; i++) array2[i] = i*2; }
static int[] static_array = new int[10];
// By contrast, the block below is a static initializer. Note the static
// keyword. It runs only once, when the class is first loaded.
static {
for(int i = 0; i < 10; i++) static_array[i] = i; }
}
Transparency No. 1-168
Basic Java Syntax
Some other notes
 Class Literals:
 Each user or system defined class is represented by an
object of the type java.lang.Class at runtime.
 Given a fully qualified class name a.b.C, there are two
ways to refer to the Class object representing a.b.C:
 1. Class.forName(“a.b.C”)
 2. a.b.C.class
 (2.) is useful for inner classes as well; as to (1.) it requires
special knowledge of how inner classes is translated into
top level classes.
 Class.forName(a.b.C$D); // a.b.C.D.class
Transparency No. 1-169
Basic Java Syntax
Default value of variables
 Kinds of variables:
1.
2.
3.
4.
5.
6.
7.
class/static variables
instance variables
local variables
formal method parameters
formal constructor parameters
array component : int[ ] ar = new int[10] ; // => ar[0] .. ar[9]
exception-handler parameters
 Notes about default value of uninitalized variables:
1. Default values are given only to array components or
class/instance variables which are not final.
2. Local variables are not assigned default values.
Transparency No. 1-170
Basic Java Syntax
Blank Final
 Blank finals
 a field or local variable declared final but without given an
initial value in the declaration.
 Recall that a final variable cannot be reassigned values
(for primitive type) or references (for array or object type)
once it has been given a content.
public class Test
{ final int y = 10 ; // y is final but not blank final.
int z ; // z is not final and has default value 0
final int x ; // x is blank final, has no value here
{ x = 1; } // x assigned value for the 1st time. ok!
Transparency No. 1-171
Basic Java Syntax
Blank final
 public void setX(int nx, final int ny) {
 x = nx; //error, final field x reassigned value.

// still error even removing {x=1;} why ?

// no way to determine if x = nx will be executed once only.








nx = nx + 10 ; // ok, nx is not final and has value
ny = ny + 10 ; // error, final ny reassigned value
final int nx10 = nx; // ok
final int nx11 ; // blank final
int nz
// local var has no default value
nx = nz + 1;
// error nz has no value here
nz = nx11 = nx; // ok
nx11 = nx; // error }}
Transparency No. 1-172
Basic Java Syntax
Object of final variable can change state.
class Person {
final Person wife = findAWife(..);
final Person[] children = new Person[5] ;
…
public void m() {
wife.name = newName(); // ok, final object changes state
wife = FindAnotherWife(…) // error! final var changes
reference
children[0] = bearOne(…); // ok! final object can change
state
children = FindChilren(..) // error!
}
Transparency No. 1-173