oop review. key oop concepts zobject, class zinstantiation, constructors zencapsulation zinheritance...
TRANSCRIPT
OOP Review
Key OOP Concepts
Object, ClassInstantiation, ConstructorsEncapsulationInheritance and SubclassesAbstractionReusePolymorphism, Dynamic Binding
Object
Definition: a thing that has identity, state, and behavior
identity: a distinguished instance of a classstate: 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 datadata/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 creationMemory is allocated for the object’s
fields as defined in the classInitialization is specified through a
constructora special method invoked when objects
are created
Encapsulation
A key OO concept: “Information Hiding”
Key pointsThe 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 relationshipB is a subclass of AB inherits all definitions
(variables/methods) in A
Abstraction
OOP is about abstractionEncapsulation and Inheritance are
examples of abstractionWhat does the verb “abstract” mean?
Reuse
Inheritance encourages software reuse
Existing code need not be rewrittenSuccessful reuse occurs only through
careful planning and designwhen defining classes, anticipate future
modifications and extensions
Polymorphism
“Many forms”allow several definitions under a single
method nameExample:
“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 ParadigmVisual Programming and GUIs
windows, icons, buttons, etc. are objects created from ready-made classes
Event-driven Programmingexecution associated with user interaction
with visual objects that causes the invocation of other objects’ methods
OOP and Object Interaction
Objects pass messages to each otherAn 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 objectDepicted in an Interaction Diagram
Java Review
What is Java?
Java is a general purpose programming language that is:object-orientedinterpreted, architecture-neutral, portabledistributed (network-aware), securesimple, robustmulti-threadedhigh-performance (?)
Two Types of Java Programs
Applicationsgeneral-purpose programsstandaloneexecuted through the operating system
Appletsprograms meant for the WWWembedded in a Web pagenormally executed through a browser
Fundamental Language Issues
Compilation and ExecutionData TypesVariablesStatementsArraysOthers
Java ProgramCompilation and Execution
Prog.java is compiled to Prog.classjavac Prog.java
Executionfor 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 typesint, double, char, float, long, boolean,
byteData type sizes
In Java, the size of a data type type is strictly specified
Sizes and Rangesfor some Java Types
int: 4 bytes-2,147,483,648 to 2,147,483,647
float: 4 bytes1.01e-45 to 3.40e+38
double 8 bytes4.94e-324 to 1.80e+308
Sizes and Rangesfor some Java Types
boolean: true, falsesize: 1 bitNot compatible with integer types as in
Cchar: Unicode character set
size: 2 bytesSuperset of ASCIIInternationalizationStill compatible with integer types
Two Kinds of Variables
Variables of a primitive typee.g., int x; char c;
Variables of a reference type (class)e.g., Button b; String s;
ConventionsPrimitive types are reserved words in Java
and are indicated in all-lower-case lettersClass names: first letter usually capitalized
Variables and Values
Primitive type variables
int x; …x = 5;
5
X
X
Variables and References
Reference type variables
Button x; …x = new Button(“copy”);
X
X
“copy”
Button Object
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
“copy”
Button Object
1023:
1023 is some address in memory
1023
X
The null Keyword
Use null to indicate (or test) that the variable does not currently refer to an object
x = null;
if (x == null) ...
null
X
Statements
Expression statementsOperations, assignment, function calls
Control structuresif, 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
6.6
nums
double nums[];
nums = new double[8];
nums[3] = 6.6;
Array of Objects
TextField objectslots
TextField object
TextField object
TextField objectTextField object
Classes and Objectsin 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 invocationobject.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 classjavap package.name.NameOfClasse.g., javap java.awt.Button, or javap
Circle
The this keyword
this refers to the current objectIn 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 objectdot operator used consistently
Constructors
A constructor is a special type of methodhas the same name as the class
It is called when an object is creatednew 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.0System.out.println(c.area());d = new Circle(1.0,1.0,5.0);// radius of circle has been set to 5.0System.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 methodthe number of parametersthe types of the parameters
Encapsulation in Java
Access modifierspublic
a public variable/method is available for use outside the class it is defined in
privatea 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 accessto private data
No direct accessDefine (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 variabledefine a get method to retrieve that
valueStill 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 Aobjects 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 AIt is legal to have variables of class A
to refer to objects of class BExample
Circle c;…c = new EnhancedCircle();
Method Overriding
A method (with a given signature) may be overridden in a subclass
Suppose class B extends Alet void operate() be a method defined
in Avoid operate() may be defined in Bobjects 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
ExampleA v; … v.operate();
Constructors and Superclasses
Suppose B extends Anew B() calls B’s constructorhow about A’s constructor ?
Rulethe constructor of a superclass is always
invoked before the statements in the subclass’ constructor are executed
super()
Used to call a superclass’ constructorImplicitly included when not indicated
If B extends A, the following are equivalent:
public B() { public B() {
// body of constructor 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
}
}