Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
ITI 1121. Introduction to Computing II†
Rafael Falcon and Marcel Turcotte(with contributions from R. Holte)
Electrical Engineering and Computer ScienceUniversity of Ottawa
Version of January 16, 2012
†Please don’t print these lecture notes unless you really need to!
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Overview
I Object-oriented programmingI Encapsulation
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Object-oriented Programming and software design
I What is object-oriented programming?
I The design of a software system is an abstract activity, inthe sense that you cannot see or touch the product that isbeing built.
I The design of software systems in terms of classes andobjects, makes this process more concrete, you canactually draw diagrams that correspond to classes and objects,or imagine the classes and objects as physical entities.
I This conceptualization allows us to think about theinteractions amongst parts of the software more easily(naturally).
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Abstraction
Abstraction allows us to ignore the details of a concept and tofocus on its important characteristics.
The term “black-box” is often used as an analogy for anabstraction.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Abstractions in Computer Science
I Variable: a symbol (label) that represents a value (a memorylocation)
I Procedure ‡: breaking a problem into sub-problems, hidingdetails of the computation, reusable
I Record §: grouping together affiliated data, modeling data
‡Sub-routine, routine, function, method§Structure (struct)
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Data abstraction
Records and structures were amongst the first forms of dataabstraction.
They allow to model the data and to handle the data as a unit.
Consider modeling a coordinate, point, in a two-dimensional plane.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Data abstraction
A point could be declared as follows:
class Point {
int x;
int y;
}
which would be used as follows:
static Point add( Point a, Point b ) {
Point result = new Point();
result.x = a.x + b.x;
result.y = a.y + b.y;
return result;
}Calling the add( ) method :
p3 = add( p1, p2 );
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Data abstraction
Imagine determining if two points are equal.
Without data abstraction, every time the information about aparticular point is to be passed to a method, you would need to listall the variables that characterize a point.
boolean equals( int x1, int y1, int x2, int y2 ) {
// ...
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Data abstraction
Whenever a change to the design has to be made (adding orremoving variables, 2D to 3D) you would have to update theprogram in several places.
The type system is not used as effectively as it could, as in theprevious example, where the formal parameters are:
equals( int x1, int y1, int x2, int y2 )
but the actual parameters are:
equals( x1, x2, y1, y2 )
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Data abstraction
Not to mention that it can be quite tedious to list all the necessaryvariables:
int equal( int x1, int y1, int y3, int x2, int y2, int y3 ) {
// ...
}
vs
int equal( Point p1, Point p2 ) {
// ...
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Is data abstraction enough?
Now consider the case of writing classes to represent differentgeometrical shapes. Attempts to draw a shape such as the onebelow are likely to occur at many places inside the programs:
if ( isCircle( shape ) ) {
drawCircle( shape );
} else if ( isSquare( shape ) ) {
drawSquare( shape );
else { // etc
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Is data abstraction enough?
if ( isCircle( shape ) ) {
drawCircle( shape );
} else if ( isSquare( shape ) ) {
drawSquare( shape );
else {
// etc
}
Image adding a new kind of shape; this would involve goingthrough all the programs that are known to use this record typeand finding all the places where you would need to add new cases;This process is rather complex since the statements acting onthe data are separated from the data;The implications of changing a record will propagate throughoutthe programs.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
A new type of abstraction in OOP
Procedural Abstraction+
Data Abstraction=
Object-Oriented Programming
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Abstraction in OOP
Procedural Abstraction+
Data Abstraction=
Object-Oriented Programming
The central concept of object-oriented programming is the object.An object consists of:
I data abstractions (variables)
I procedural abstractions (methods)
A software system consists of a collection of objectsinteracting together to solve a common task.
(Java is an object-oriented programming language)
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Examples
I E-commerce: customers, items, inventory, transactions,journal . . . ;
I Chess game: pieces, board, users;
I Factory: production lines, robots, items, parts, . . . ;
We see that for some objects , there is only one “instance” — thisis the case for the board in the chess game application.For others, there will be many objects of the same “class”, allsharing the same properties and behaviours.However, each of these objects is unique and has a state (thecurrent values of its attributes) that may or may not be the sameas other objects.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Object
An object has:
I attributes: describe its current state;
I behaviours: what it can do in response to internal/externalrequests.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Unified Modeling Language (UML)
A standard graphical language for modeling object-orientedsoftware; developed in the mid-1990s.A class diagram is represented by a three-band box: the name ofthe class, the attributes and the methods.
+ getHours(): int+ getMinutes(): int+ getSeconds(): int
+ hours: int+ minutes: int+ seconds: int
Time
Further notation will be introduced along with concepts.⇒ Simon Benett, Steve McRobb and Ray Farmer (1999)Object-Oriented Systems Analysis and Design using UML.McGraw-Hill.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Counter
Perhaps the simplest object to describe is the Counter. Imaginethe kind of device used e.g. at baseball games to keep track of thescores, strikes, etc.The device that I envision has a window that displays the currentvalue and a single button, which increases the value of the counterby 1 every time it is pressed.A counter has to have a state, which is the current value of thecounter.There has to be a way to read the content of the counter.There has to be a way to increase the value of the counter (andmaybe a way to reset the value - another button).
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Counter: a naive approach
A single value has to be recorded!
Furthermore, the value can be represented with one of theprimitive data types of Java such as int or long.
Here is a counter:
int counter1;
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Counter: a naive approach
I can initialize it and increase its value whenever I want or need to:
counter1 = 0;
counter1++; // stands for counter1 = counter1 + 1
I can have as many counters as I want. Here is a new counter:
int counter2;
I can even have a whole array of them:
int[] counters;
counters = new int[5];
⇒ What is the problem then?
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Counter: a naive approach
The problem is that it is not modeling the concept of a counterappropriately. Nothing prevents us from increasing the value by asmuch as we want:
counter1 = counter1 + 5;
// ...
counter1 = counter1 - 1;
// ...
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Counter: OOP to the rescue
public class Counter {
private int value = 0;
public int getValue() {
return value;
}
public void incr() {
value++;
}
public void reset() {
value = 0;
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Counter: OOP to the rescue
public class Test {
public static void main( String[] args ) {
Counter counter = new Counter();
System.out.println( "counter.getValue()->"
+counter.getValue() );
for ( int i=0; i<5; i++ ) {
counter.incr();
System.out.println( "counter.getValue()->"
+counter.getValue() );
}
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Counter: OOP to the rescue
public class Test {
public static void main( String[] args ) {
Counter counter = new Counter();
System.out.println( "counter.getValue()->"
+counter.getValue() );
for ( int i=0; i<5; i++ ) {
counter.incr();
System.out.println( "counter.getValue()->"
+counter.getValue() );
}
counter.value = -9;
}
}
Test.java:13: value has private access in Counter
counter.value = -9;
^R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class
What goes into a class?Let’s try to simplify things by looking at the elements of a classsystematically.Inside a class you can find:
I variables, methods, nested classes;
I each belongs either to the class or to an instance;
I each can be public, package, protected or private;
I each can be final or not.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class
How do you declare a class variable?
How do you declare an instance variable?
Did you notice that you have to put more effort to create a classvariable? By default, a variable, a method or a nested classbelongs to an instance (object) of that class.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class
How do you decide if you need to have an instance or a classvariable?
Can you mention an example that helps understanding thedifference between instance and class variables?
An instance variable defines the state of an object.
What do you mean by state?
I am defining the state of an object as the current values of itsinstance variables.
Think about the class Counter! The class Time, etc.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class variables
public class Ticket {
private static int lastSerialNumber = 0;
private int serialNumber;
public Ticket() {
serialNumber = lastSerialNumber;
lastSerialNumber++;
}
public int getSerialNumber() {
return serialNumber;
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class variables
java.lang.Math provides many examples of static variables andmethods.
public class Math {
public static final double E = 2.7182818284590452354;
static int min( int a, int b )
static double sqrt( double a )
static double pow( double a, double b )
public static double toDegrees(double angrad) {
return angrad * 180.0 / PI;
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class
How do you call a class method? Similarly, how do you access aclass variable?
I Within the class where the member is defined, simply use thename of the method or variable;
I Otherwise, if it is a class member, prefix the name of themember by the name of the class;
Math.sqrt( 36 );
Math.min( a, b );
I Otherwise, use a reference to an object of the class thatcontains this member.
Counter c;
c = new Counter();
if ( c.getValue() < c.MAX_VALUE / 2 ) { ... }
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class vs instance method
What would be the impact of declaring a class method as aninstance method?
I example: Math
What would be the impact of declaring an instance method as aclass method?
I example: Counter
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Package
In order to understand the visibility modifiers, we need tointroduce the notion of package first.
What is a package?
A package is an organizational unit that allows to group classes;
A package contains one or more related classes.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Package
E.g. The Java API (Application Programming Interface) isstructured into packages.
java.io
java.lang
java.util
java.awt
Do you remember “import java.io.*;” from your ITI 1120 course?
Packages may contain other packages. This is convenient, but ithas no semantic. E.g.
java.awt
java.awt.color
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Package
A class has access to the other classes of the same package.
datebook
datebook.agenda
Event
Agenda
datebook.util
Time
TimeInterval
By default, a class is visible only to the other classes of the samepackage.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Package
The organization of the packages also corresponds to theorganization of the files and directories on the disk.File: datebook/util/Time.java
package datebook.util;
class Time {
...
}
File: datebook/agenda/Event.java
package datebook.agenda;
public class Event {
...
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Package
By default, a class is not accessible to classes from other packages.File: datebook/util/Time.java
package datebook.util;
class Time {
...
}
File: datebook/agenda/Event.java
package datebook.agenda;
import datebook.util.Time;
public class Event {
private Time start;
}
Cannot be compiled!
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Package
You have to declare the Time class as public so that it can bevisible from another package.File: datebook/util/Time.java
package datebook.util;
public class Time {
...
}
File: datebook/agenda/Event.java
package datebook.agenda;
import datebook.util.Time;
public class Event {
private Time start;
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Package
Why would you define a class that would not be public?
This would be a class used only by the classes of the package (animplementation detail).
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Package
Packages are not only useful for grouping classes. They areextremely useful to avoid or resolve name conflicts!
E.g. Event is defined in datebook.agenda.Event as well as injava.awt.Event!
Declaring a reference of type java.awt.Event:
java.awt.Event e;
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Package
Finally, if a class is not assigned to a specific package, it belongs toan “unnamed package”.
A package declaration is used to specify the name of the packageto which the class belongs.
package datebook.util;
public class Time {
...
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Visibility modifiers
I public: Member accessible from everywhere.
I package: Member accessible by any class in the samepackage.
I protected: Member accessible by any class in the samepackage or by any subclass regardless of its package.
I private: Member accessible only by the class that declares it.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Final
The final keyword can also be placed in front of a variable. A finalvariable can only be initialized once, either via an initializer or anassignment statement.
public class Circle {
public static final double PI = 3.14159;
public final double x;
public final double y;
public final double radius;
public Circle(int xPos, int yPos, aRadius) {
x = xPos;
y = yPos;
radius = aRadius;
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Modeling Time
Let’s define a class to represent a Time in terms of the following:
hours: integer, 0 . . . 23 (inclusively)
minutes: integer, 0 . . . 59 (inclusively)
seconds: integer, 0 . . . 59 (inclusively)
⇒ two implementations will be considered.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time Class
Are there mandatory parts?
Do we have to have variables? Methods? Constructor?
A class starts with the class keyword followed by the name of theclass, which is any valid Java identifier. Usually, it is a singularnoun that starts with a capital letter.
class Time {
}
Is this a valid class declaration?
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time Class
Yes, this can be saved to a file named Time.java and compiled.Let’s try:
> javac Time.java
produces Time.class.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time Class
What does it buy us? Can it be used?How about this:
class Test {
public static void main( String[] args ) {
Time t;
}
}
Yes, a reference to an object of the Time class can be declared.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time Class
How about this?
class Test {
public static void main( String[] args ) {
Time t;
t = new Time();
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Constructor
What is a constructor?
I A constructor is a block of statements that are executed whenan object is created;
I A constructor has the same name as its class;
I A constructor can have arity 0, 1, 2, etc.
I Can only be called once, when the object is created, in thecontext of “new . . . ”;
I A constructor has no return type.
Since the constructor is called when the object is firstcreated, it is commonly used to initialize the instancevariables.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Constructor
Does it make sense to declare a private constructor?
class Coordinates {
int myX;
int myY;
public Coordinates(int x){
this(x, 0);
}
private Coordinates(int x, int y) {
myX = x;
myY = y;
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time Class: Constructor
Hum, the Time class does not even have a constructor.
Java provides you with a default constructor.
class Time {
Time() {
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time Class: Attributes
Recall that Time must represent a time value. What are theattributes?
Hours, minutes and seconds (instance or class variables?)
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time Class: Constructor
The default constructor exists unless you create your ownconstructor! Given the following definition:
class Time {
int hours; int minutes; int seconds;
Time( int h, int m, int s ) {
hours = h;
minutes = m;
seconds = s;
}
}
The second statement will produce a compile-time error.
Time t;
t = new Time();
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class Interface
The public variables and methods are defining the interface of theclass.
To use an object (or a class) all you need to know is its interface.
The interface must be carefully designed.
Changes to the public methods and variables (i.e. the interface)will affect the other classes that are part of this software system.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
The class as a specification
class Time {
int hours;
int minutes;
int seconds;
Time( int h, int m, int s ) {
hours = h;
minutes = m;
seconds = s;
}
}
All objects of the Time class will have 3 attributes: hours,minutes and seconds, as well as a default constructor Time().
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time−hours: int−minutes: int−seconds: int
+getHours(): int+getMinutes(): int+getSeconds(): int+toString(): String+equals(t:Time): boolean+increase(): void−normalize(): void
hours=11minutes =38seconds = 21
hours=11minutes =39seconds = 43
hours=13minutes =12seconds = 55
hours=14minutes = 20seconds = 0
instance of
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Creating objects
An object is created 1) with the use of the reserved keyword newand 2) a call to a special method that has the same name as theclass. That special method is called a constructor. It never returnsa result and may have 0 or more formal parameters.
a = new Time(13,0,0);
b = new Time(14,30,0);
...
n = new Time(16,45,0);
n objects of the Time class have been created.The Time class was used to create n objects.There is a 1 : n relationship between the class and its objects.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Creating objects
a = new Time(13,0,0);
When creating an object, say a, from a class, here Time, we saythat a is an instance of the Time class.Here is Webster’s definition of an instance:
“(. . . ) instance: an individual illustrative of a category”
⇒ . . . in a sense, an object is an example of a class.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Creating an object, let’s be more precise
Time a;
a = new Time(13,0,0);
To be more precise, we should say that a is a reference variablethat points to an instance of the Time class.
Variables have types!
Objects have class(es)!
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
> Time a;
a = new Time(16,45,0);
class Time
a null
⇒ The declaration of a reference, here a reference to an object ofthe Time class, tells the compiler to reserve enough space to holda reference (an address, a pointer) to an object.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time a;
> a = new Time(16,45,0);
class Time
int minutes = 45;int seconds = 0;
int hours = 16;
Time( ... );int getHours();
a null
⇒ At runtime, the execution of new Time(16,45,0) creates anobject of the Time class, calls the constructor Time(int,int,int)which initializes the instance variables of the object; an objectknows which class it belongs to, this is symbolized by the arrowhere.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time a;
> a = new Time(16,45,0);
class Time
int minutes = 45;int seconds = 0;
int hours = 16;
Time( ... );int getHours();
a
⇒ At runtime, the assignment statement a = ..., writes thereference (“address”) of the object at the location designated by a.In other words, a now points to the object.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Any particular problem?
With the current definition of the Time class, it’s possible for theuser to assign a value that would be out of range:
For example:
Time a = new Time( 13,0,0 );
a.hours = 55;
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Solution
Object-oriented programming languages give us tools to controlthe “access to”/“visibility of” the data and methods, this principleis called information hiding.
class Time {
private int hours;
private int minutes;
private int seconds;
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
What will happen?
public class Time {
private int hours;
private int minutes;
private int seconds;
}
class Test {
public static void main( String[] args ) {
Time a = new Time( 1, 2, 3 );
System.out.println( a.hours );
}
}
The compiler will complain that hours has private access:
Main.java:6: hours has private access in Time
System.out.println (a.hours);
^R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Access methods
Since we no longer have access to the variables from outside theclass, methods must be introduced to return the content of theinstance variables:
int getHours () {
return hours;
}
which will be used as follows:
a = new Time( 13,0,0 );
System.out.println( a.getHours() );
-> 13
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Access methods
public int getHours() {
return hours ;
}
public int getMinutes() {
return minutes ;
}
public int getSeconds() {
return seconds ;
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
How about setters?
Should access methods be systematically created for each instancevariable to assign a new value (setter)?
public void setHours( int h ) {
hours = h;
}
No! Each problem has its own design issues. Here, we require thatthe value of a time object can only be changed by using theincrement( ) method that will increase the time represented bythis object by one second.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
The equals( ) method
public class Time {
private int hours;
private int minutes;
private int seconds;
// ...
public boolean equals( Time t ) {
return (( hours == t.getHours() ) &&
( minutes == t.getMinutes() ) &&
( seconds == t.getSeconds() ) ) ;
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
How about this?
public class Time {
private int hours;
private int minutes;
private int seconds;
// ...
public boolean equals( Time t ) {
return (( hours == t.hours ) &&
( minutes == t.minutes ) &&
( seconds == t.seconds ) ) ;
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Another problem to be fixed
There remains a problem with the current definition: it is possiblethat the initial values would be out of range:
Time a = new Time( 24,60,60 );
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Solution
Since the constructor is called (executed) when an object is firstcreated, it is hence the ideal place to implement the mechanismsthat will ensure that the initial values are in the correct range.Let’s create a new method which will do the job of normalizing thevalues of the instance variables:
public Time(int hours, int minutes, int seconds) {
this.seconds = seconds;
this.minutes = minutes;
this.hours = hours;
normalize();
}
new Time (0,0,60) -> 0:1:0
new Time (0,59,60) -> 1:0:0
new Time (23,59,60) -> 0:0:0
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
normalize()
private void normalize () {
int carry = seconds / 60;
seconds = seconds % 60;
minutes = minutes + carry ;
carry = minutes / 60;
minutes = minutes % 60;
hours = (hours + carry) % 24;
}
This method is intended to be used only by the methods of theTime class, hence its visibility is set to private.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
public void increase() {
seconds++ ;
normalize();
}
⇒ normalize () can be used at other places too.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
public String toString()
public String toString() {
return hours + ":" + minutes + ":" + seconds;
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Summary
We have considered the declarative aspect of a class, i.e. the classspecifies the characteristics that are common to an ensemble ofobjects.
All the variables and methods that we have defined belong to theinstance; they were instance methods and instance variables.Consequently:
I each object (instance) has its own set of instance variables(sometimes called attributes), this means that each objectreserves space for its own set of attributes;
I an instance method can access the content of the instancevariables, you can think about this as if the method wereexecuted inside the object.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class variables and methods
We now consider the dynamic aspect of a class.
The class is also a runtime entity; memory is allocated for it duringthe execution of the program.
Remember, we said earlier that there is a 1 : n relationship betweenthe class and its instances. In particular, this means there is onlyone copy of a class in memory for n instances, a class variable isvariable whose space is allocated into the class, and therefore thisvariable is unique and shared by all instances of the class.
Similarly, a class method is a method that belong to the class,there is only one copy of it and it can only access the classvariables (not the instance variables).
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class variables and methods
Class variables and methods are declared with the use of thereserved keyword static.
How to determine if a variable should be a class variable or aninstance variable?
Constants should always be class variables. By definition, aconstant will not change throughout the execution of the programand therefore can be shared by all the instances of a class.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Class variables
class Time {
// class variables (these are constants,
// notice the final keyword)
static public final int HOURS_PER_DAY = 24;
static public final int MINUTES_PER_HOUR = 60;
static public final int SECONDS_PER_MINUTE = 60;
// instance variables
private int hours;
private int minutes;
private int seconds;
...
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Time−hours: int−minutes: int−seconds: int+HOURS_PER_DAY: int = 24+MINUTES_PER_HOURS: int = 60+SECONDS_PER_MINUTES: int = 60
+getHours(): int+getMinutes(): int+getSeconds(): int+toString(): String+equals(t:Time): boolean+increase(): void−normalize(): void
hours=11minutes =38seconds = 21
hours=11minutes =39seconds = 43
hours=13minutes =12seconds = 55
hours=14minutes = 20seconds = 0
instance of
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
class Time {
static public final int HOURS_PER_DAY = 24;
static public final int MINUTES_PER_HOUR = 60;
static public final int SECONDS_PER_MINUTE = 60;
private int hours ; // 0 - 23 (inclusively)
private int minutes ; // 0 - 59 (inclusively)
private int seconds ; // 0 - 59 (inclusively)
...
}
There are 2 ways to access class variables:1- via the class:
System.out.print(Time.HOURS_PER_DAY);
=> 24
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
2- via an instance:
Time t = new Time (13,0,0);
System.out.print(t.HOURS_PER_DAY);
=> 24
t →
hours = 13minutes = 0seconds = 0Time (int hours, int minutes, int seconds)String toString ()
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
What’s this?
“this” is a self-reference.
BankAccount example
public class BankAccount {
private double balance;
// ...
public boolean transfer(BankAccount other, double amount) {
if (this == other)
return false;
...
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
angelina.transfer( brad, 100 )
45,000,000
angelina
balance
otherthis
100,000,000
brad
balance
Call framefor the methodtransfer
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
angelina.transfer( brad, 100 )
45,000,000
angelina
balance
otherthis
100,000,000
brad
balance
Call framefor the methodtransfer
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
45,000,000
angelina
balance
otherthis
100,000,000
brad
balance
Call framefor the methodtransfer
brad.transfer( angelina, 100 )
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
45,000,000
angelina
balance
other
angelina.transfer( angelina, 100 )
this
100,000,000
brad
balance
Call framefor the methodtransfer
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
What’s this?
public class Date {
private int day;
private int month;
public Date( int day, int month ) {
this.day = day;
this.month = month;
}
// ...
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
What’s this?
[ New !!!! ]Don’t use instance variables where local variables would do the job,why?
1. Wrong design - it shows that you don’t understand thedifferent kinds of variables well
2. Each object uses more memory than it needs too, and it willdo so for the rest of its life
3. It gets into the way of the garbage collector
class A {
int[] boxes;
putObjectsIntoBoxes () {
boxes = new int[ 1000 ];
}
}
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Resources
Java Language Specification(syntax and semantics of the language)java.sun.com/docs/books/jls/second edition/html/jTOC.doc.html
JavaTM 2 Platform API SpecificationStandard Edition, v 1.4.2(libraries)java.sun.com/j2se/1.4.2/docs/api
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
References I
E. B. Koffman and Wolfgang P. A. T.Data Structures: Abstraction and Design Using Java.John Wiley & Sons, 2e edition, 2010.
P. Sestoft.Java Precisely.The MIT Press, second edition edition, August 2005.
D. J. Barnes and M. Kolling.Objects First with Java: A Practical Introduction Using BlueJ.Prentice Hall, 4e edition, 2009.
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II
Please don’t print these lecture notes unless you really need to!
R. Falcon and M. Turcotte ITI 1121. Introduction to Computing II