oop review. key oop concepts zobject, class zinstantiation, constructors zencapsulation zinheritance...

58
OOP Review

Upload: valentine-oneal

Post on 13-Jan-2016

233 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

OOP Review

Page 2: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Key OOP Concepts

Object, ClassInstantiation, ConstructorsEncapsulationInheritance and SubclassesAbstractionReusePolymorphism, Dynamic Binding

Page 3: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 4: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 5: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 6: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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)

Page 7: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 8: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Abstraction

OOP is about abstractionEncapsulation and Inheritance are

examples of abstractionWhat does the verb “abstract” mean?

Page 9: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 10: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 11: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 12: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 13: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Java Review

Page 14: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

What is Java?

Java is a general purpose programming language that is:object-orientedinterpreted, architecture-neutral, portabledistributed (network-aware), securesimple, robustmulti-threadedhigh-performance (?)

Page 15: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 16: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Fundamental Language Issues

Compilation and ExecutionData TypesVariablesStatementsArraysOthers

Page 17: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 18: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 19: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Data Types

Primitive typesint, double, char, float, long, boolean,

byteData type sizes

In Java, the size of a data type type is strictly specified

Page 20: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 21: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 22: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 23: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Variables and Values

Primitive type variables

int x; …x = 5;

5

X

X

Page 24: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Variables and References

Reference type variables

Button x; …x = new Button(“copy”);

X

X

“copy”

Button Object

Page 25: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 26: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 27: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 28: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Arrays

Declaration: double nums[];Creation: nums = new double[8];Use: nums[3] = 6.6;

* Note: starting index is 0 (0 to 7, above)

Page 29: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Visualizing an Array

6.6

nums

double nums[];

nums = new double[8];

nums[3] = 6.6;

Page 30: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Array of Objects

TextField objectslots

TextField object

TextField object

TextField objectTextField object

Page 31: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Classes and Objectsin Java

Page 32: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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());

Page 33: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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; }}

Page 34: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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()); }}

Page 35: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 36: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 37: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 38: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 39: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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; } ...}

Page 40: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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 } ...}

Page 41: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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());

Page 42: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 43: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 44: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 45: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 46: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 47: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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; } // ...}

Page 48: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Inheritance

Page 49: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 50: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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; }

}

Page 51: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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();

Page 52: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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();

Page 53: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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()

Page 54: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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();

Page 55: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

Page 56: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

}

Page 57: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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);

} …

}

Page 58: OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

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

}

}