Transcript Java Review

OOP Review
Key OOP Concepts
Object, Class
Instantiation, Constructors
Encapsulation
Inheritance and Subclasses
Abstraction
Reuse
Polymorphism, Dynamic Binding
Object
Definition: a thing that has identity, state,
and behavior
identity: a distinguished instance of a class
state: collection of values for its variables
behavior: capability to execute methods
* variables and methods are defined in a class
Class
Definition: a collection of data (fields/
variables) and methods that operate on
that data
data/methods define the
contents/capabilities of the instances
(objects) of the class
a class can be viewed as a factory for
objects
a class defines a recipe for its objects
Instantiation
Object creation
Memory is allocated for the object’s fields
as defined in the class
Initialization is specified through a
constructor
a special method invoked when objects are
created
Encapsulation
A key OO concept: “Information Hiding”
Key points
The user of an object should have access
only to those methods (or data) that are
essential
Unnecessary implementation details should
be hidden from the user
In Java, use classes and access modifiers
(public, private, protected)
Inheritance
Inheritance:
Programming language feature that allows
for the implicit definition of variables/methods
for a class through an existing class
Subclass relationship
B is a subclass of A
B inherits all definitions (variables/methods)
in A
Abstraction
OOP is about abstraction
Encapsulation and Inheritance are
examples of abstraction
What does the verb “abstract” mean?
Reuse
Inheritance encourages software reuse
Existing code need not be rewritten
Successful reuse occurs only through
careful planning and design
when defining classes, anticipate future
modifications and extensions
Polymorphism
“Many forms”
allow several definitions under a single
method name
Example:
“move” means something for a person
object but means something else for a car
object
Dynamic binding:
capability of an implementation to
distinguish between the different forms
during run-time
Visual and Event-driven
Programming
Fits very well with the OO Paradigm
Visual Programming and GUIs
windows, icons, buttons, etc. are objects
created from ready-made classes
Event-driven Programming
execution associated with user interaction
with visual objects that causes the invocation
of other objects’ methods
OOP and Object Interaction
Objects pass messages to each other
An object responds to a message by
executing an associated method defined
in its class
Causes a “chain reaction”
The user could be viewed as an object
Depicted in an Interaction Diagram
Java Review
What is Java?
Java is a general purpose programming
language that is:
object-oriented
interpreted, architecture-neutral, portable
distributed (network-aware), secure
simple, robust
multi-threaded
high-performance (?)
Two Types of Java
Programs
Applications
general-purpose programs
standalone
executed through the operating system
Applets
programs meant for the WWW
embedded in a Web page
normally executed through a browser
Fundamental Language
Issues
Compilation and Execution
Data Types
Variables
Statements
Arrays
Others
Java Program
Compilation and Execution
Prog.java is compiled to Prog.class
javac Prog.java
Execution
for applets, the browser loads Prog.class
(specified in html file) and UI events can then
be processed
for applications, a Java interpreter loads
Prog.class and causes program execution to
begin in the “main()” method of this class
The Java Virtual Machine
Browsers and the Java interpreters have
to simulate this “standard” machine
“Compile once, run anywhere”
Class Loader
The JVM facilitates the loading and
execution of classes
Several classes, not just one class, are
loaded
Java class library
Data Types
Primitive types
int, double, char, float, long, boolean, byte
Data type sizes
In Java, the size of a data type type is
strictly specified
Sizes and Ranges
for some Java Types
int: 4 bytes
-2,147,483,648 to 2,147,483,647
float: 4 bytes
1.01e-45 to 3.40e+38
double 8 bytes
4.94e-324 to 1.80e+308
Sizes and Ranges
for some Java Types
boolean: true, false
size: 1 bit
Not compatible with integer types as in C
char: Unicode character set
size: 2 bytes
Superset of ASCII
Internationalization
Still compatible with integer types
Two Kinds of Variables
Variables of a primitive type
e.g., int x; char c;
Variables of a reference type (class)
e.g., Button b; String s;
Conventions
Primitive types are reserved words in Java
and are indicated in all-lower-case letters
Class names: first letter usually capitalized
Variables and Values
Primitive type variables
int x;
…
x = 5;
X
X
5
Variables and References
Reference type variables
X
Button x;
…
x = new Button(“copy”);
Button Object
X
“copy”
The new Keyword
new Button(“copy”) creates a Button
object and returns a reference (an
address) to that object that a Button
variable could hold
Button Object
X
1023
1023:
1023 is some address in memory
“copy”
The null Keyword
Use null to indicate (or test) that the
variable does not currently refer to an
object
x = null;
if (x == null) ...
X
null
Statements
Expression statements
Operations, assignment, function calls
Control structures
if, switch, while, do-while, for, try-catch (for
exception handling)
In a compound statement or block ({…}),
variable declarations and statements may
intersperse
Arrays
Declaration: double nums[];
Creation:
nums = new double[8];
Use:
nums[3] = 6.6;
* Note: starting index is 0 (0 to 7, above)
Visualizing an Array
nums
nums = new double[8];
6.6
double nums[];
nums[3] = 6.6;
Array of Objects
slots
TextField object
TextField object
TextField object
TextField object
TextField object
Classes and Objects
in Java
Variables and Objects
Let Circle be a class with:
variable r that indicates its radius
method area() that computes its area
Declaration:
Circle c;
Instantiation:
c = new Circle();
Usage:
c.r = 5.5;
System.out.println(c.area());
The complete Circle class
public class Circle {
public double x,y; // center coordinates
public double r; // radius
// the methods
public double circumference()
{ return 2*3.14*r; }
public double area() { return 3.14*r*r; }
}
Using the Circle class
public class TestCircle {
public static void main(String args[]) {
Circle c;
c = new Circle();
c.x = 2.0; c.y = 2.0; c.r = 5.5;
System.out.println(c.area());
}
}
The Dot (“.”) Operator
Allows access to variables (primitive and
reference types) and methods of
reference type variables.
Example:
TextField t = new TextField(10);
t.setText(“hi”); // accessing the setText method
Method Invocation
Syntax for method invocation
object.methodName(arguments)
Method may return a value or simply
produce an effect on the object
To find out what methods are available for
a given class
javap package.name.NameOfClass
e.g., javap java.awt.Button, or javap Circle
The this keyword
this refers to the current object
In the Circle class, the following
definitions for area() are equivalent:
public double area() { return 3.14 * r * r; }
public double area() { return 3.14 * this.r * this.r; }
Using the keyword clarifies that you are
referring to a variable inside an object
dot operator used consistently
Constructors
A constructor is a special type of
method
has the same name as the class
It is called when an object is created
new Circle(); // “calls” the Circle() method
If no constructor is defined, a default
constructor that does nothing is
implemented
A constructor for the
Circle class
public class Circle {
public double x,y; // center coordinates
public double r; // radius
public Circle() {
// sets default values for x, y, and r
this.x = 0.0; this.y = 0.0; this.r = 1.0;
}
...
}
A constructor with
parameters
public class Circle {
…
public Circle(double x, double y, double z) {
this.x = x; this.y = y; this.r = z;
// using this is now a necessity
}
...
}
Using the different
constructors
Circle c, d;
c = new Circle();
// radius of circle has been set to 1.0
System.out.println(c.area());
d = new Circle(1.0,1.0,5.0);
// radius of circle has been set to 5.0
System.out.println(d.area());
Method Overloading
In Java, it is possible to have several
method definitions under the same name
 but the signatures should be different
Signature:
the name of the method
the number of parameters
the types of the parameters
Encapsulation in Java
Access modifiers
public
a public variable/method is available for use
outside the class it is defined in
private
a private variable/method may be used only
within the class it is defined in
The Circle class Revisited
public class Circle {
private double x,y; // center coordinates
private double r; // radius
// ...
}
// when using the Circle class ...
Circle c;
c.r = 1.0; // this statement is not allowed
Outside access
to private data
No direct access
Define (public) set and get methods
instead or initialize the data through
constructors
Why?
If you change your mind about the names
and even the types of these private data, the
code using the class need not be changed
Set and Get Methods
Variables/attributes in a class are often
not declared public
Instead:
define use a (public) set method to assign a
value to a variable
define a get method to retrieve that value
Still consistent with encapsulation
Set and Get Methods for
Radius
public class Circle {
// ...
private double r; // radius
// …
public void setRadius(double r) { this.r = r; }
public double getRadius() { return this.r; }
// ...
}
Inheritance
Inheritance and the
extends Keyword
In Java,
public class B extends A { … }
means B is a subclass of A
objects of class B now have access* to
variables and methods defined in A
The EnhancedCircle class
public class EnhancedCircle extends Circle {
// as if area(), circumference(), setRadius() and getRadius()
// automatically defined; x,y,r are also present (but are private
// to the the Circle class)
private int color;
public void setColor(int c) { this.color = c; }
public void draw() { … }
public double diameter() {
return this.getRadius()*2; }
}
Using a Subclass
EnhancedCircle c;
c = new EnhancedCircle();
// Circle() constructor
// implicitly invoked
c.setColor(5);
c.setRadius(6.6);
System.out.println(c.area());
System.out.println(c.diameter());
c.draw();
Superclass Variables,
Subclass Objects
Let B be a subclass of A
It is legal to have variables of class A to
refer to objects of class B
Example
Circle c;
…
c = new EnhancedCircle();
Method Overriding
A method (with a given signature) may be
overridden in a subclass
Suppose class B extends A
let void operate() be a method defined in A
void operate() may be defined in B
objects of class A use A’s operate()
objects of class B use B’s operate()
Dynamic Binding
Let A be a superclass of subclasses B and
C
A variable of class A may refer to
instances of A, B, and C
Java facilitates the calling of the
appropriate method at run time
Example
A v; … v.operate();
Constructors and
Superclasses
Suppose B extends A
new B() calls B’s constructor
how about A’s constructor ?
Rule
the constructor of a superclass is always
invoked before the statements in the
subclass’ constructor are executed
super()
Used to call a superclass’ constructor
Implicitly included when not indicated
If B extends A, the following are equivalent:
public B() {
// body of constructor
}
public B() {
super();
// body of constructor
}
Calling a particular
Constructor
Use super with parameters if a particular
constructor should be called
Example:
public class BlueButton extends Button {
public BlueButton(String s) {
super(s); // without this, super() is called (label-less)
setBackground(Color.blue);
}…
}
More Uses for super
When overriding a method, one can
merely “extend” the method definition
public class Manager extends Employee {
public void increase() {
super.increase(); // call Employee’s increase
// do more stuff
}
}