Object-oriented Programming - Department of Computer Science

Download Report

Transcript Object-oriented Programming - Department of Computer Science

COM S 228
Introduction to Data Structures
Instructor: Ying Cai
Department of Computer Science
Iowa State University
[email protected]
Office: Atanasoff 201
Office Hours: MW 3:00pm-4:00pm
Information Hiding Modularity
The basic idea is to build systems out of components
that can be developed independently of each other
Reducing coupling between components is the key
developing complex systems, not just software
Abstraction
View components in terms of their essential features,
ignoring details that aren’t relevant to our particular
concerns
Each component provides a well-defined interface that
specifies exactly how we can interact with it
Object-Oriented Programming
A system is a collection of interacting objects
that communicate through well-defined
interfaces
An object has three components
State: instance variables that hold some values
Identity: an object can be referred to and unique
identified
Operations: public interfaces (application
programming interface)
A class is a type of an object
A class may have many objects
OOP in Java: Class and Object
Program
File
File
Class
File
Variables
Constructors Variables
File
Statements
Methods
Variables
Statements
A program consists of
one or more classes
In java, a class typically
takes a single file
Point example
BankAccount examples
class BankAccount
{
// account state stored in private variables
private float balance;
private String name;
private String TransactionList;
// etc
// public interface
public void deposit(float amount) {
…
}
public double getCurrentBalance() {
…
}
public double getTransactionList () {
…
}
public Report prepareMonthlyReport() {
…
}
// etc
}
Interface
An interface in Java defines a set of public
methods without bodies


For each method, it specifies a method name,
parameter types, and return types
It is basically a contract between module writers,
specifying exactly how they will communicate
Interface Implementation
An interface is basically a contract between
module writers
Bird is called a subtype of ISpeaking
and ISpeaking a supertype of Bird
Other Implementations
A same interface can have more than one
implementation
Some Notes
You can declare an object whose type is an
interface:
ISpeaking b; //OK
You cannot instantiate an interface variable
ISpeaking b = new Ispeaking(); //illegal
An interface variable must refer to an object of
a class that implements the interface
ISpeaking b = new Bird(); //OK
All methods in a java interface are public
Implementation of Multiple Interfaces
Class Extension
Share code and reduce redundancy
Allow to add new attributes and methods
Retriever is a subtype or subclass of Dog;
Dog is a supertype or a superclass of Retriever
Class Hierarchy
By extension, classes may form a hierarchy
Class hierarchy may be described as a class diagram,
using Unified Modeling Language (UML)
We say Dog “implements” ISpeaking (dot line), Retriever extends Dog (solid line)
We also say the subtype relation the “is-a” relation: A Retriever is a type of Dog, and
a Dog is a type of ISpeaking.
Polymorphism
A variable of a given type T can hold a reference to an
object of any of T’s subtypes
Ispeaking s = new Dog(“Thunder”, null)
The above statement does a few things
It invokes a constructor to instantiate an object of type Dog 
Some amount of memory is allocated to hold this object
The constructor returns a reference to the object (or actually
points to the memory address)
It declares a variable s of type Ispeaking
The value of s is set to be the reference (i.e., memory address)
Important Notes
A Dog can be referenced by s because every Dog is an ISpeaking
object, but not vice verse
In general, an object can hold a reference to any of its subtype
Static Type vs. Dynamic Type
Let p be a reference to an object
Static type (compile time type) of P is the type of P
when it is declared
Dynamic type (runtime type) of P is the type of the
object it references
Dog dog = new Dog();
Bird bird = new Bird();
ISpeaking s = null;
s
s
d
b
=
=
=
=
dog; // OK?
bird; // OK?
s; // OK?
s; // OK?
Dynamic binding
Let p be a reference to an object
When p’s method is invoked, it is the object’s method
that gets invoked
Suppose we also want to implement a Cat class
now getName() is duplicated
Abstract Class and Abstract Method
The idea is to eliminate duplicated code
Java Abstract classes are used to declare
common characteristics of subclasses. An
abstract class cannot be instantiated. It
can only be used as a superclass for
other classes that extend the abstract
class. Abstract classes are declared with
the abstract keyword. Abstract classes
are used to provide a template or design
for concrete subclasses down the
inheritance tree.
Allow different implementation of speak() for different pets
Updated Class Hierarchy
More Example
Implementation through Interface
Abstract Class and Abstract Method
A Java interface is just like an abstract class,
except
• A java class can inherit from only class, but can
implement multiple interfaces
• A Java interface cannot implement any method,
it can only contain method prototypes and
constants
Access Modifiers
private
• Accessible only within the class, used for
implementation details
none or “package-private” (almost = protected)
• Accessible from any class within the package or by a
subclass of its class in another package
protected
• Accessible from subclasses, use when you want any
subclass to have access to a variable or method that
is not public
public
• Accessible from any class
The root of java class hierarchy:
java.lang.object
• toString(): return a string
containing the class name
and a hex number
• getClass(): return the object
of type Class that represents
the runtime class of the
object
• equals(): return if two objects
are the same, i.e., in the
same memory
Memory Allocation
Variable of primitive types
• Value reference: It references to a memory that store the
actual value
• 8 types (byte, short, int, long, float, double, boolean, char)
int i = 100;
• Allocate at most 8 bytes
Variable of non-primitive types (i.e., objects)
• Object reference: It references to a memory that stores the
address of the memory that stores the object
• Depending on the implementation of JVM, most likely 8 bytes
(for 64-bit address space)
Object o = new Object();
Array
• treated as an object
int a[] = new int[100];
Object o[] = new Object[100];
// what does this mean?
Point r = q;
Point r = new Point(1, 2);
Point q = new Point(1, 2);
r.equals(q)?
String s = “hurry”;
String t = “HURRY”.toLowerCase()
System.out.println(s == t);
System.out.println(s.equals(t);
Copy and Clone()
//1. Using constructor
pubic Point(Point existing)
{
this.x = existing.getX();
this.y = existing.getY();
}
Copy and Clone()
//2. Ad hoc cloning
pubic Point makeClone()
{
Point copy = new Point();
copy.setX(this.x);
copy.setY(this.y);
}
Copy and Clone()
//2. Ad hoc cloning
pubic Point makeClone()
{
Point copy = new Point();
copy.setX(this.x);
copy.setY(this.y);
}
Uaage:
Point p = new Point(2, 4);
q = p.makeClone();
Copy and Clone()
//3. Overriding Object.clone()
pubic Object clone()
{
Point copy = null;
try
{ // super.clone() creats a copy of
// all fileds
copy = (Point) super.clone();
}
catch (CloneNotSupportedException e)
{
}
return copy;
}
Shallow vs Deep Copying
public class IntVector {
// Dimension (length) of this vector.
private int dim;
//The coordinates of this vector.
private int[] coords;
::::
public IntVector(IntVector existing)
{
dim = existing.dim;
coords = new int[dim];
for (int i = 0; i < dim; ++i)
{
coords[i] = existing.coords[i];
}
}
}
Static Variables
 Also called class variables
 Shared by a whole class of objects
Static Method
 Does not implicit pass an object as its
parameter
Usage: Human.printHumans()
Variable Scope
 The scope of a variable is the part of the program in
which it is visible
 Local variable: defined within a method, ranged from
its declaration until the end of the block or for
statement in which it is declared
public static void main(String[] args)
{
int sum = 0;
for (int i=0; i<=10; i++)
{
int square = i * i;
sum = sum + square;
}
System.out.println(sum);
}
Exception Handling
 An exception is any special condition that alters the
normal flow of program execution

divided by zero or open a file that does not exist, etc.
Exception handler