OO vocabulary

advertisement
OO vocabulary
 Class
A class defines a data type, which describes the
pattern of data and behavior. This new type may be
used to create objects of that type.
 Object or instance
A variable of a particular class
 Messaging
We say that you “send a message” to ask object to
perform an action
 Method
“function” for a class, it is the code body that
implements a message
What is 10 miles?
10 mi = 16 km
User
Interface
16
miToKm(10)
MiToKm
object
User
Exercise: Run and understand MiToKmTest.java
(together with MyInput.java)
1
Defining a class
Time.java, TimeTest0.java, and Time.Test1.java
will be used as examples in the discussion.
 Time class is defined in Time.java file
o Class name must match filename, case matters
o Class definition cannot be split among multiple files
o Only one public class defined per file
 Class file is both interface and implementation
o No separate header files, unlike C
 Instance variables
o Fields or data in the “object struct”
 Instance methods
o Object operations, functions that are strongly tied to
class
 Order of definition doesn’t matter
o Can refer to variables/methods that appear lexically
afterwards
2
Class example
public class Time {
private int hour, minute;
public int getHour {
return hour;
}
// accessor method
public void setHour(int newValue) {
hour = newValue;
} // mutator method
public int getMinute() {
return minute;
}
public void setMinute(int newValue) {
minute = newValue;
}
}
3
Java Modifiers
Modifier
(default)
class
X
method
X
data
X
X
X
X
private
X
X
protected
X
X
static
X
X
X
public
final
X
X
abstract
X
X
native
X
synchronized
X
Explanation
A class, method, or data is
visible in this package.
A class, method, or data field is
visible to all the programs in
any package.
A method or data field is only
visible in this class.
A method, or data field is
visible in this package and in
subclasses of this class in any
package.
Defines a class method or a
class data field.
A final class cannot be
extended. A final method
cannot be modified in a
subclass. A final data field is a
constant.
An abstract class must be
extended. An abstract method
must be implemented in a
concrete subclass.
A native method indicates that
the method is implemented
using a language other than
Java.
Only one thread at a time can
execute this method
4
Controlling Access to Members of a Class
 An access specifier determines whether other classes can
use a particular member variable or call a particular method
 public
o Accessible to everyone, both designer and users of the
class
o Public instance variables frowned upon
 private
o Accessible only within class implementation, only
class designer
 protected
o Similar to private, but also visible in subclasses
(classes that are designed based on this one)
 default (when you list no keyword) is “friendly”
o Public within this package, but private outside it
Specifier of a Class
member
itself
within a
class
Private
x
No specifier
x
protected
x
public
x
Package
(classes in
the same
package)
x
x
x
Subclasses World
of the class
x
x
x
Two Considerations:
1. Access levels of the source determines which members of
the classes your class can use
2. When you write a class, you need to decide what access
level every member variable / method in your class should
have.
5
Storage for objects
 A Time object has two instance variables
 Object about same size as comparable structure
 Creating a Time object allocates the space
Time t = new Time();
 Each Time object has its own distinct copies of the instance
variables
 When messaging an object or accessing fields, you are
referring to a particular object’s copy of the fields
6
Sending a message
 Public members accessed using “.“, similar to accessing a
field within a C struct
 Using a public variable
Time t = new Time();
t.hour = 3; //allowable if hour is public
 Sending a public message
Time t = new Time();
t.setHour(3);
System.out.println(”The hour is “ +
t.getHour());
 Object you are messaging is called the receiver
 Accessing non-public variable/method outside class will
raise a compiler error
7
Implementing a method
 Methods are implemented as part of class definition
 Within a method, all variables/methods are visible
public void shiftBy(int deltaHr, int
deltaMin) {
hour += deltaHr;
minute += deltaMin;
}
 Can send messages to a receiving object
public void shiftBy(int deltaHr, int
deltaMin) {
setHour(hour + deltaHr);
setMinute(minute + deltaMin);
}
 A method may need to refer to the object that invoked it.
Use the keyword this inside any method to refer to the
current object.
public void clear() {
this.hour = 0;
this.setMinute(0);
}
8
Maintaining object consistency
 Setters can be constrained to correct range
public void setHour(int newValue) {
if (newValue < 0) hour = 0;
//constraint
else if (newValue > 23) hour = 23 ;
else hour = newValue;
}
public void setMinute(int newValue) {
minute = newValue % 60; // wrap into range
}
 What if the instance variables were public?
 What is the advantage of making all accesses, even inside
implementation, go through setters?
 Should the setters themselves be public?
9
Creating Objects
(three operations in one line)
 Declaration: It is a variable declaration that
associates a name with a type.
 Instantiation: new is a Java operator that
creates the new object (allocates space for it).
 Initialization: The new operator is followed by
a call to a constructor.
Point point = null;
point = new Point( 72, 115 );
or
Point point = new Point( 72, 115 );
10
Object allocation
 Newly declared variable starts as a null reference
Time t;
// t has value null
 Use new to create new object
t = new Time(); // t now refers to a new Time instance
o Fields in a new object are zeroed by default
 Objects are implemented as references
o Like arrays, these are “pointers in disguise”
 Assignment between objects doesn’t make a “deep
copy”, it makes another reference to same object
Time u = t ;
u.setHour(10) ;
System.out.print(“The hour is = “+ t.getHour());
11
Constructors
 Special method to initialize newly created object
 Part of new operator, so allocation and initialization are
always done together
 Constructor must have exact same name as class
 Has no declared return type and can’t return anything
 Access control applies as for other methods
o What would happen if constructor were declared
private?
 Constructors can have parameters and can be overloaded
Constructor example
 Add a constructor to Time class
public Time(int hr, int min)
{
hour = hr;
minute = min;
}
 Can message receiving object, even in constructor
public Time(int hr, int min)
{
setHour(hr);
setMinute(min);
}
 Now give arguments to new which calls constructor
Time t = new Time(9, 15);
12
Cleaning up
 Java doesn’t have destructors analogous to C++
 Garbage collector takes care of deallocating storage
 What if you have more cleanup to do? (free resources, like
fonts, files, etc.,)
 finalize method called when storage reclaimed
protected void finalize(){
System.out.println(“I’m outta here”) ;
}
 protected prevents access outside the class (package)
 called by Java run time before garbage collection.
 Not guaranteed to be called in timely manner
o Not guaranteed to be called at all, actually!
 If you need guaranteed cleanup, add your own method and
call explicitly yourself
13
Overloading and constructors
 Can overload constructor, like any other method
 Constructor can chain to other constructor
public Time(int hr) {
this(hr, 0);
}
// syntax a little weird
 Resolves best/closest match to how call is made
t
t
t
t
=
=
=
=
new
new
new
new
Time(3, 15);
Time(5);
Time();
Time(”3:00”);
//
//
//
//
2-arg version
1-arg version
doesn’t compile!
nope either!
 Default constructor, only if no constructors defined at
all
o Default zero-arg constructor that just clears (zeros) all
instance variables (or sets to specified default values)
14
Field initialization, default values
 Can assign default values when defining ivars
public class Time {
private int hour = 12, minute = 30;
 Doesn’t have to be constant expression
private int hour = Math.random()*12;
 This initialization takes place before constructor
o Replaces initialization to zero for default constructor
 Assignment happens in order of declaration
 Any advantage over assigning in constructor?
15
The final modifier for variables
 final makes a variable “read-only”
o Variable is assigned once and cannot change value
after that
o Used to define constants
o Could add final variables to the Time class for
constraints
public class Time {
private final int MinHour = 0, MaxHour = 23;
private int hour, minute;
. . . .
 This means each Time object now has 4 variables
o Two for its own hour and mm, and two more for final
variables
o It would be better to share these last two values for all
Time objects instead of making individual copies for
each
16
Static final variables
 static applied to a variable makes it “class-wide”
o Only one piece of storage for all instances , shared by
all
 Class constants done with static and final together
public class Time {
private static final int MinHr = 0, MaxHr = 23;
private int hour, minute;
 This is more efficient way to organize the data
o Each Time object has only 2 variables, class variables
shared
 Also used to build enum-like entries
public class Time {
public static final int AM = 0, PM =1;
o Accessed outside like this: Time.AM
 Is it safe/good for anything final to be public?
17
The static modifier for variables
 Static is one-per-class instead of one-per-instance
 Access specifiers still apply
o public static variables accessible to all, private only
inside class
 Not all static variables must be final
 Example: class variable tracks count of objects created
public class Time {
public static int numObjectsCreated = 0;
public Time(int hour, int minute) {
numnObjectsCreated++;
//increment count in constructor
. . . . . . .
 Access field of class itself, instead of instance
System.out.print(”Num “+ Time.numObjectsCreated());
18
The static modifier for methods
 static keyword makes a method class-wide
 Example: create accessor for private static data
public class Time {
private static int numObjectsCreated = 0;
static public int numCreated() {
return numObjectsCreated;
}
 Send message to class, not to instance
System.out.print(”Num “+ Time.numCreated() );
 Static methods used as substitute for functions
Math.random(), Math.abs(),
Character.isLowerCase(), etc.
19
More on static methods
 Static methods have no “this”
o Within static method, cannot access instance variables
or call instance methods
 Instance methods can access static, though
o Within instance method, can call static methods,
access static vars
o Can’t declare instance and class variable/method of
same name
o When field accessed without explicit receiver,
assumed to mean “this” or “thisClass”
Time t = new Time();
int count = t.numCreated(); // ok
int hour = Time.getHour(); // not ok
20
Singleton design pattern
 Only want one instance ever created, shared by all
public class Clipboard {
private Clipboard() {
// private ctor
. . . . .
}
private static Clipboard sharedInstance;
public static Clipboard getSharedInstance()
{
if (sharedInstance == null)
sharedInstance = new Clipboard();
return sharedInstance;
}
}
 Clients use static method to get shared instance
Clipboard clip = Clipboard.getSharedInstance();
Another static final example
 Want each instance assigned a unique id, start from 1
public class Time {
private static int nextID = 1;
private final int myID = nextID++;
o could also have assigned myID in ctor, no big
difference
 When object created
o Assigns its own id number (final so cannot be
changed)
o Increments class variable for next one
21
Compile-time type checking
 Java is considered a strongly-typed language
o All variables, parameters must declare type (int,
String, Time, etc.)
 Can use variable only in ways that respect type
o e.g. cannot divide Time by float or assign String
into int
 Cannot message an object with wrong message
o String has length method, Time does not
Time t = new Time();
System.out.println( t.length() );
o This produces compile-time error
 All object expressions type-checked
o Both accessing a variable or sending a message
o Variable or method must exist, be accessible, and
match type usage
22
Basic thoughts on object design
 Never let object get into malformed state
o No public instance variables
o Always set up state properly in constructor and/or
defaults values
o Only provide setters if needed, be sure properly
constrained
o Don’t hand out references to mutable internal data
 Object should be responsible for own behavior. Interface
should include complete set of needed methods
o Need to print Time? Add print method to class,
don’t pull out the hour/minute fields and do it yourself
o Same for converting a string to Time, comparing two
times, shifting a time forward, etc.
o Does every ivar need a setter? A getter?
23
Internal vs external representation
 To client, might be handy that Time works in terms of
hours and minutes
 But this is a difficult representation to manipulate
o What about AM/PM?
o How to add delta to time, how to handle wrap?
 Even a simple operation like before can be quirky
boolean before(Time other) { // note access to other
return ((this.hour < other.hour) ||
(this.hour == other.hour &&
this.minute < other.minute) );
}
 Is there a better way?
24
More on representation
 If Time stored in military 24-hour time?
o Somewhat easier to shift, avoids problems with
AM/PM
 If internally tracked as minutes since midnight..?
o Trivial to implementation “before” operation
o Trivial to shift, easy to handle wrap around as well
 Can still provide accessor for hour/minute if needed
o Simple to compute from internal representation
 Does changing the internal data affect client of Time
class?
o What impact does making things public have on
implementation flexibility?
o What is “deprecated” about anyway?
Exercise: Run FormatDemo.java to understand text formatting
Run TimeTest0.java (with Time.java)
Run TimeTest1.java (with Time.java)
Run CreateObjectDemo.java (together with Point.java
and Rectangle.java).
Question: Since Point and Rectangle are graphics, why
CreateObjectDemo.java will compile as is?
Any criticism on the way the program is written?
25
The Growth of the Java Standard Edition API
version # classes/interfaces
1.0
212
1.1
504
1.2
1781
1.3
2130
1.4
3020
# methods/fields
2125
5478
20935
23901
32138
26
Download