Lecture 2 - Object Oriented Conceptx
Download
Report
Transcript Lecture 2 - Object Oriented Conceptx
Introduction to ObjectOriented Concept
Object-Oriented Technology and
Development
Concept: An object
has behaviors
In old style programming, you had:
data, which was completely passive
functions, which could manipulate any data
An object contains both data and methods that
manipulate that data
An object is active, not passive; it does things
An object is responsible for its own data
• But: it can expose that data to other objects
2
An object has state
An object contains both data and methods that
manipulate that data
The data represent the state of the object
Data can also describe the relationships between
this object and other objects
Example: A CheckingAccount might have
A balance (the internal state of the account)
An owner (some object representing a person)
3
Example: A “Rabbit”
object
You could (in a game, for example) create an
object representing a rabbit
It would have data:
How hungry it is
How frightened it is
Where it is
And methods:
eat, hide, run, dig
4
Concept: Classes describe objects
Every object belongs to (is an instance of) a class
An object may have fields, or variables
The class describes those fields
An object may have methods
The class describes those methods
A class is like a template, or cookie cutter
You use the class’s constructor to make objects
5
Concept: Classes are like
Abstract Data Types
An Abstract Data Type (ADT) bundles together:
some data, representing an object or "thing"
the operations on that data
The operations defined by the ADT are the only
operations permitted on its data
Example: a CheckingAccount, with operations
deposit, withdraw, getBalance, etc.
Classes enforce this bundling together
If all data values are private, a class can also
enforce the rule that its defined operations are the
only ones permitted on the data
6
Example of a class
class Employee {
// Fields
private String name; //Can get but not change
private double salary; // Cannot get or set
// Constructor
Employee(String n, double s) {
name = n; salary = s;
}
// Methods
void pay () {
System.out.println("Pay to the order of " +
name + " $" + salary);
}
public String getName() { return name; } // getter
}
7
Approximate
Terminology
instance = object
field = instance variable
method = function
sending a message to an object =
calling a function
These are all approximately true
8
Concept: Classes form a hierarchy
Classes are arranged in a treelike structure called a
hierarchy
The class at the root is named Object
Every class, except Object, has a superclass
A class may have several ancestors, up to Object
When you define a class, you specify its superclass
If you don’t specify a superclass, Object is assumed
Every class may have one or more subclasses
9
Example of (part of)
a hierarchy
Container
Panel
ScrollPane
Window
Dialog
Frame
FileDialog
A FileDialog is a Dialog is a Window is a Container
10
C++ is different
In C++ there may be more than one root
but not in Java!
In C++ an object may have more than one parent
(immediate superclass)
but not in Java!
Java has a single, strict hierarchy
11
Concept: Objects
inherit from
superclasses
A class describes fields and methods
Objects of that class have those fields and
methods
But an object also inherits:
the fields described in the class's superclasses
the methods described in the class's superclasses
A class is not a complete description of its
objects!
12
Example of inheritance
class Person {
String name;
int age;
void birthday () {
age = age + 1;
}
}
class Employee
extends Person {
double salary;
void pay () { ...}
}
Every Employee has name and age fields and
birthday method as well as a salary field and a pay
method.
13
Concept: Objects
must be created
int n; does two things:
It declares that n is an integer variable
It allocates space to hold a value for n
For a primitive, this is all that is needed
Employee secretary; also does two things
It declares that secretary is type Employee
It allocates space to hold a reference to an Employee
For an object, this is not all that is needed
secretary = new Employee ( );
This allocate space to hold a value for the Employee
Until you do this, the Employee is null
14
Notation: How to declare
and create objects
Employee secretary; // declares secretary
secretary = new Employee (); // allocates space
Employee secretary = new Employee(); // does both
But the secretary is still "blank" (null)
secretary.name = "Adele"; // dot notation
secretary.birthday (); // sends a message
15
Notation: How to
reference a field or
method
Inside a class, no dots are necessary
class Person { ... age = age + 1; ...}
Outside a class, you need to say which object you
are talking to
if (john.age < 75) john.birthday ();
If you don't have an object, you cannot use its
fields or methods!
16
Concept: this object
Inside a class, no dots are necessary, because
you are working on this object
If you wish, you can make it explicit:
class Person { ... this.age = this.age + 1; ...}
this is like an extra parameter to the method
You usually don't need to use this
17
Concept: A variable can
hold subclass objects
Suppose B is a subclass of A
A objects can be assigned to A variables
B objects can be assigned to B variables
B objects can be assigned to A variables, but
A objects can not be assigned to B variables
• Every B is also an A but not every A is a B
You can cast: bVariable = (B) aObject;
In this case, Java does a runtime check
18
Example: Assignment of
subclasses
class Dog { ... }
class Poodle extends Dog { ... }
Dog myDog;
Dog rover = new Dog ();
Poodle yourPoodle;
Poodle fifi = new Poodle ();
myDog = rover;
yourPoodle = fifi;
myDog = fifi;
yourPoodle = rover;
yourPoodle = (Poodle) rover;
// ok
// ok
//ok
// illegal
//runtime check
19
Concept: Methods can be
overridden
class Bird extends Animal {
void fly (String destination) {
location = destination;
}
}
class Penguin extends Bird {
void fly (String whatever) { }
}
So birds can fly. Except penguins.
20
Concept: Don't call
functions, send messages
Bird someBird = pingu;
someBird.fly ("South America");
Did pingu actually go anywhere?
You sent the message fly(...) to pingu
If pingu is a penguin, he ignored it
Otherwise he used the method defined in Bird
You did not directly call any method
You cannot tell, without studying the program,
which method actually gets used
The same statement may result in different
methods being used at different times
21
Sneaky trick: How to use
overridden methods
class FamilyMember extends Person {
void birthday () { // override birthday() in Person
super.birthday (); // call overridden method
givePresent ();
// and add your new stuff
}
}
22
Constructors
A constructor is a special method designed to
initialize instance variables
Automatically called when an object is created using
new
Has the same name as the class
Often overloaded (more than one constructor for the
same class definition)
different versions to initialize all, some, or none of the
instance variables
each constructor has a different signature (a different
number or sequence of argument types)
Defining
Constructors
Constructor headings do not
include the word void
In fact, constructor headings do not
include a return type
A constructor with no parameters is
called a default constructor
If no constructor is provided Java
automatically creates a default
constructor
If any constructor is provided, then no
constructors are created automatically
Constructor Example
public class Pet
{
private String name;
private int age; //in years
private double weight; //in pounds
. . .
public Pet (String initialName)
{
name = initialName;
age = 0;
Initializes three instance
weight = 0;
variables: name from the
}
parameter and age and weight
with default initial values.
Sample use:
Pet pet1 = new Pet(“Eric”);
Using Constructors
Always use a constructor after new
For example, using the Pet class in text:
Pet myCat = new Pet("Calvin", 5, 10.5);
this calls the Pet constructor with String, int,
double parameters
If you want to change values of instance
variables after you have created an object,
you must use other methods for the object
you cannot call a constructor for an object after it is
created
set methods should be provided for this purpose
Concept: Constructors make objects
Every class has a constructor to make its objects
Use the keyword new to call a constructor
secretary = new Employee ( );
You can write your own constructors; but if you
don’t,
Java provides a default constructor with no
arguments
It sets all the fields of the new object to zero
If this is good enough, you don’t need to write your own
The syntax for writing constructors is almost like
that for writing methods
27
Syntax for constructors
Do not use a return type and a name; use only the
class name
You can supply arguments
Employee (String theName, double theSalary) {
name = theName;
salary = theSalary;
}
28
Trick: Give field and parameter the same name
A parameter overrides a field with the same name
But you can use this.name to refer to the field
class Person {
String name;
int age;
Person (String name, int age) {
this.name = name;
this.age = age;
}
}
Using the same name is a common and useful convention
29
Internal workings:
Constructor chaining
If an Employee is a Person, and a Person is an
Object, then when you say new Employee ()
The Employee constructor calls the Person
constructor
The Person constructor calls the Object constructor
The Object constructor creates a new Object
The Person constructor adds its own stuff to the
Object
The Employee constructor adds its own stuff to the
Person
30
The case of the vanishing
constructor
If you don't write a constructor for a class, Java
provides one (the default constructor)
The one Java provides has no arguments
If you write any constructor for a class, Java does
not provide a default constructor
Adding a perfectly good constructor can break a
constructor chain
You may need to fix the chain
31
Example: Broken
constructor chain
class Person {
String name;
Person (String name) {
this.name = name;
}
}
class Employee extends Person {
double salary;
Employee ( ) {
super();
salary = 12.50;
}
}
Java tries to
execute an implicit
super() at this
point
cannot resolve symbol – constructor Person()
32
Fixing a broken
constructor chain
Special syntax: super(...) calls the superclass constructor
When one constructor calls another, that call must be first
class Employee {
double salary;
Employee (String name) {
super(name); // must be first
salary = 12.50;
}
}
Now you can only create Employees with names
This is fair, because you can only create Persons with
names
33
Trick: one constructor
calling another
this(...) calls another constructor for this same class
class Something {
Something (int x, int y, int z) {
// do a lot of work here
}
Something ( ) { this (0, 0, 0); }
}
It is poor style to have the same code more than once
If you call this(...), that call must be the first thing in your
constructor
34
Access Modifier
class Person {
public String name;
private String age;
protected double salary;
public void birthday { age++; }
}
Each object is responsible for its own data
Access control lets an object protect its data
and its methods
Access control is the subject of a different
lecture
35
Concept: Classes can
have fields and methods
Usually a class describes fields (variables) and methods
for its objects (instances)
These are called instance variables and instance methods
A class can have its own fields and methods
These are called class variables and class methods
There is exactly one copy of a class variable, not one per
object
Use the special keyword static to say that a field or
method belongs to the class instead of to objects
36
Example of a class variable
class Person {
String name;
int age;
static int population;
Person (String name) {
this.name = name;
this.age = 0;
population++;
}
}
37
Advice: Restrict access
Always, always strive for a narrow interface
Follow the principle of information hiding:
the caller should know as little as possible about
how the method does its job
the method should know little or nothing about
where or why it is being called
Make as much as possible private
Your class is responsible for it’s own data; don’t
allow other classes to screw it up!
38
Setters and Getters
class Employee extends Person {
private double salary;
private boolean male;
public void setSalary (double newSalary) {
salary = newSalary;
}
public double getSalary () { return salary; }
public boolean isMale() { return male; }
}
This way the object maintains control
Setters and getters have conventional names:
setDataName, getDataName, isDataName (booleans only)
39
Kinds of access
Java provides four levels of access:
public: available everywhere
protected: available within the package (in the
same subdirectory) and to all subclasses
[default]: available within the package
private: only available within the class itself
The default is called package visibility
In small programs this isn't important...right?
40
The "this." Operator
this. refers to the object that contains
the reference
Methods called in an object definition
file do not need to reference itself
public may
class either
Oracle use "this.", or omit it,
You
{
since
... it is presumed
//One
way to invoke
the answerOne method
defined
For
example,
if answerOne()
is a method
//in thisin
file:
defined
the this.answerOne();
class Oracle:
//Another way is to omit "this."
answerOne(); //"this." is presumed
...
}
When an Object Is
Required
Methods called outside the object definition
require an object to precede the method
name
For example:
Oracle myOracle = new Oracle();
//myOracle is not part of the definition code
//for Oracle
...
//dialog is a method defined in Oracle class
myOracle.dialog();
...
Static Methods
Some methods do work but do not need
an object
For example, methods to calculate area:
just pass the required parameters and return the
area
Use the class name instead of an object
name to invoke them
For example
CircleFirstTry is a class with methods to
perform calculations on circles:
CircleFirstTry.area(myRadius);
Notice that the the method invocation uses
"className." instead of " circleObject."
Also called class methods
Static Methods
Declare static methods with the static modifier,
for example:
public static double area(double radius) ...
Since a static method doesn’t need a calling
object, it cannot refer to a (nonstatic) instance
variable of the class.
Likewise, a static method cannot call a nonstatic
method of the class (unless it creates an object of
the class to use as a calling object).
Uses for Static
Methods
Static methods are commonly used to provide
libraries of useful and related functions
Examples:
the Math class
• automatically provided with Java
• functions include pow, sqrt, max, min, etc.
• see the next slide for more details
SavitchIn defines methods for keyboard input
• not automatically provided with Java
• functions include readLineInt, readLineDouble, etc
The Math Class
Includes constants Math.PI (approximately 3.14159) and Math.E
(base of natural logarithms which is approximately 2.72)
Includes three similar static methods: round, floor, and ceil
All three return whole numbers (although they are type double)
Math.round returns the whole number nearest its argument
Math.round(3.3) returns 3.0 and Math.round(3.7) returns 4.0
Math.floor returns the nearest whole number that is equal to or
less than its argument
Math.floor(3.3) returns 3.0 and Math.floor(3.7) returns 3.0
Math.ceil (short for ceiling) returns the nearest whole number that
is equal to or greater than its argument
Math.ceil(3.3) returns 4.0 and Math.ceil(3.7) returns 4.0
Static Variables
The StaticDemo program in the text uses a static
variable:
private static int numberOfInvocations = 0;
Similar to definition of a named constant, which is a
special case of static variables.
May be public or private but are usually private for
the same reasons instance variables are.
Only one copy of a static variable and it can be
accessed by any object of the class.
May be initialized (as in example above) or not.
Can be used to let objects of the same class
coordinate.
Not used in the rest of the text.
Wrapper Classes
Used to wrap primitive types in a class structure
All primitive types have an equivalent class
The class includes useful constants and static
methods, including one to convert back to the
primitive type
Primitive type Class type
Method to convert back
int
Integer
intValue()
long
Long
longValue()
float
Float
floatValue()
double
Double
doubleValue()
char
Character
charValue()
Wrapper class
example: Integer
Declare an Integer class variable:
Integer n = new Integer(42);
Convert the value of an Integer variable
to its primitive type, int:
int i = n.intValue();//intValue returns
an int
Some useful Integer constants:
Integer.MAX_VALUE - the maximum integer
value the computer can represent
Integer.MIN_VALUE - the smallest integer value
the computer can represent
Wrapper class
example: Integer
Some useful Integer methods:
Integer.valueOf("123") to convert a
String of numerals to an Integer
Integer.toString(123) to convert an
Integer to a String
The other wrapper classes have similar
constants and functions
See the text for useful methods for the
class Character
Usage of wrapper classes
There are some important differences in the code to
use wrapper classes and that for the primitive types
Wrapper Class
variables contain the
address of the value
variable declaration
example:
Integer n = new
Integer();
variable declaration &
initialize:
Integer n = new
Integer(0);
assignment:
n = new Integer(5);
Primitive Type
variables contain the
value
variable declaration
example:
int n;
variable declaration &
initialize.:
int n = 0;
assignment:
n = 99;
Designing Methods:
Top-Down Design
In pseudocode, write a list of subtasks that the
method must do.
If you can easily write Java statements for a subtask,
you are finished with that subtask.
If you cannot easily write Java statements for a
subtask, treat it as a new problem and break it up
into a list of subtasks.
Eventually, all of the subtasks will be small enough
to easily design and code.
Solutions to subtasks might be implemented as
private helper methods.
Top-down design is also known as divide-andconquer or stepwise refinement.
Programming Tips for
Writing Methods
Apply the principle of encapsulation and
detail hiding by using the public and
private modifiers judiciously
If the user will need the method, make it part of the
interface by declaring it public
If the method is used only within the class definition
(a helper method), then declare it private
Create a main method with diagnostic
(test) code within a class's definition
run just the class to execute the diagnostic program
when the class is used by another program the
class's main is ignored
Testing a Method
Test programs are sometimes called driver programs
Keep it simple: test only one new method at a time
driver program should have only one untested method
If method A uses method B, there are two approaches:
Bottom up
test method B fully before testing A
Top down
test method A and use a stub for method B
A stub is a method that stands in for the final version and
does little actual work. It usually does something as trivial as
printing a message or returning a fixed value. The idea is to
have it so simple you are nearly certain it will work.
Overloading
The same method name has more than one
definition within the same class
Each definition must have a different
signature
different argument types, a different number of
arguments, or a different ordering of argument types
The return type is not part of the signature and
cannot be used to distinguish between two methods
with the same name and parameter types
Signature
the combination of method name and
number and types of arguments, in order
equals(Species) has a different signature
than equals(String)
same method name, different argument types
myMethod(1) has a different signature than
myMethod(1, 2)
same method name, different number of arguments
myMethod(10, 1.2) has a different signature
than myMethod(1.2, 10)
same method name and number of arguments, but
different order of argument types
Overloading and Argument Type
Accidentally using the wrong datatype as an
argument can invoke a different method
For example, see the Pet class in the text
set(int) sets the pet's age
set(double) sets the pet's weight
You want to set the pet's weight to 6 pounds:
• set(6.0) works as you want because the argument is type
double
• set(6) will set the age to 6, not the weight, since the
argument is type int
Gotcha: Automatic Type Conversion
and Overloading
If Java does not find a signature match, it attempts some
automatic type conversions, e.g. int to double
An unwanted version of the method may execute
In the text Pet example of overloading:
What you want: name "Cha Cha", weight 2, and age 3
But you make two mistakes:
1. you reverse the age and weight numbers, and
2. you fail to make the weight a type double.
set("Cha Cha", 2, 3) does not do what you want
• it sets the pet's age = 2 and the weight = 3.0
Why?
• set has no definition with the argument types String, int, int
• However, it does have a definition with String, int, double,
so it promotes the last number, 3, to 3.0 and executes the method with that
signature
Information Hiding
Revisited
Using instance variables of a class type takes
special care
The problem stems from the fact that, unlike
primitive types, object identifiers contain the
object's address, not its value
returning an object gives back the address, so the
called method has direct access to the calling
object
the calling object is "unprotected" (usually
undesirable)
best solution: cloning
One solution: stick to returning primitive types (int,
char, double, boolean, etc.) or String
Packages
A way of grouping and naming a collection of
related classes
they serve as a library of classes
they do not have to be in the same directory as your
program
The first line of each class in the package must be
the keyword package followed by the name of the
package:
package mystuff.utilities;
To use classes from a package in a program put
an import statement at the start of the file:
import mystuff.utilities.*;
note the ".*" notation
Package Naming
Conventions
Use lowercase
The name is the file pathname with
subdirectory separators ("\" or "/",
depending on your system) replaced by
dots
For example, if the package is in a file
named "utilities" in directory "mystuff",
the package name is:
mystuff.utilities
Java Packages
Application programmer interface
(API)
All classes provided to programmers along with the
Java compiler (e.g. Math or MouseEvent)
Java expects to find these classes in separate
directories or folders
The classes stored in each directory
form a package
The package names are formed by
concatenating the directory names
starting from a particular root
directory
Some Predefined Java Packages
Package Name
Contents
java.applet
Classes for implementing applets
java.awt
Classes for graphics, windows, and GUI’s
java.awt.event
Classes supporting AWT event handling
java.awt.image
Classes for image handling
java.awt.peer
Interface definitions s for platform independent
graphical user interfaces (GUI’s)
java.io
Classes for input and output
java.lang
Basic language classes like Math
(always available in any Java program)
java.net
Classes for networking
java.util
Useful auxiliary classes like Date
Package Component
Names
Using a fully qualified component
name
x = java.lang.Math.sqrt(3);
Using an import statement
// to allow unqualified references to
// all package classes
import package.name.*;
// to allow unqualified references to
// a particular package class
import package.name.class_name;
Import
Examples
This code
java.util.Date d =
new java.util.Date();
java.awt.Point p =
new java.awt.Point(1,2);
java.awt.Button b =
new java.awt.Button();
Can be abbreviated
import java.util.date;
Import java.awt.*;
…
Date d = new Date();
Point p = new Point(1,2);
Button b = new Button();
Creating Your
Own Packages
Each package class must be stored in a
file in an appropriately named directory
The source code file for each package
class must contain a package statement
as its first non-commented statement
package package_name;
Several packages can be stored in the
same directory
Classes in different directories cannot be
part of the same package
Visibility Rules and
Packages
Instance variables declared as public or private have
the same visibility to classes in other packages
Instance variables without explicitly declared
visibility have package visibility
Instance variables with package visibility are only
visible to methods defined in classes belonging to
the same package
Similarly for static variables, instance methods, and
static methods having package visibility
Classes not explicitly declared public are not visible
outside the package
Inheritance
Allows programmers to customize a
class for a specific purpose, without
actually modifying the original class
(the superclass)
The derived class (subclass) is
allowed to add methods or redefine
them
The subclass can add variables, but
cannot redefine them
Inheritance
Example
Class C is a subclass of class B (its
superclass) if its declaration has the
form
class C extends B {
…
}
The subclass is a specialization of the
superclass
The superclass is a generalization of
the subclass
Inheritance and
Messages
When C is a subclass of B
C objects can respond to all messages that B
objects can respond to
In general C objects can be used whenever B
objects can be used
It is possible the a subclass of B
may have methods and variables
that have not been defined in B
It is the case B objects may not always be used in
place of C objects
Inheritance
Hierarchy
A class may have several subclasses and each
subclass may have subclasses of its own
The collection of all subclasses descended
from a common ancestor is called an
inheritance hierarchy
The classes that appear below a given class in
the inheritance hierarchy are its descendants
The classes that appear above a given class in
the inheritance hierarchy are its ancestors
Inheritance and
Visibility Rules
Private variables and methods are not
visible to subclasses or clients
Public variables and methods are visible to
all subclasses and clients
Variables and methods with package
visibility are only visible to subclasses and
clients defined in the same package as the
class
A variable or method declared with the
protected visibility modifier can only be
referenced by subclasses of the class and
no other classes
Visibility and Inheritance
Visibility
Public
default
protected
private
Clients in same
package
C
C
C
None
Clients in different
packages
C
None
None
None
Subclass in same
package
C&R
C&R
C&R
None
Subclass in
different package
C&R
None
R
None
Note: R is receiver; C is client
Overriding vs
Overloading
A method is overloaded if it has multiple
definitions that are distinguished from one
another by having different numbers or types
of arguments
A method is overridden when a subclass
gives a different definition of the method with
the same number and types of arguments
Constructors
The general rule is that when a subclass is
created Java will call the superclass
constructor first and then call the subclass
constructors in the order determined by the
inheritance hierarchy
If a superclass does not have a default
constructor with no arguments, the subclass
must explicitly call the superclass
constructor with the appropriate arguments
Using super( ) Call
Constructor
The call to super must be the first
statement in the subclass constructor
Example:
class C extends B {
…
public C ( … ) {
super( B’s constructor arguments );
…
}
…
Calling Overridden Superclass
Methods from Subclassess
The following code generates an infinite loop
because toString( ) is interpreted as this.toString( )
public void toString() {
String result = toString();
return (result + “:” + second);
}
To make a call toString in the superclass instead
public void toString() {
String result = super.toString();
return (result + “:” + second);
}
Creation of Subclass
Instances
Assuming that PreciseClock is a subclass of the
Clock class, the following is legal
Clock dawn;
dawn = new PreciseClock(3,45,30);
The instance variable dawn will respond to all
PreciseClock messages
It is not legal to write this since Clock objects cannot
respond to all PreciseClock messages
PreciseClock dawn;
dawn = new Clock(3,40);
Static and
Dynamic Binding
Static Binding
Determining which method will be invoked to respond
to a message at compile time
Dynamic Binding
Determining which method will be invoked to respond
to a message at run time
Required when method definitions are overridden in
subclasses, since type of the receiver class may not
be known until run time
Abstract Classes
Abstract classes are only used as super
classes
Classes are declared as abstract classes only
if they will never be instantiated
Abstract classes contain usually one or more
abstract methods
Example:
public abstract class Mouse implements Direction
{
…
abstract void makeMove( );
}
Abstract Methods
Abstract methods have no body at all and
just have their headers declared
The only way to use an abstract class is to
create a subclass that implements each
abstract method
Concrete classes are classes that implement
each abstract method in their superclasses
Example:
abstract void makeMove( );