Survey							
                            
		                
		                * Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
COMP 248
OBJECT ORIENTED PROGRAMMING I
Chapter 5: More on Classes
1
THIS CHAPTER…
1.
static members
2.
Wrapper classes
References
Mutable and Immutable Classes
javadoc
3.
4.
5.
2
1. STATIC MEMBERS
Members can be:
public / private / protected / package
static (class members) / non-static (instance members)
Instance members (non static)
associates a variable or method with each object
invoked through the name of a specific object
myAccount.deposit(10);
system.out.print(yourCoin.face);
Class members (static)
associates a variable or method with each class (shared by all objects of the
class)
invoked through the name of the class
System.out.print(Math.sqrt(25));
if (Character.isUpperCase(’a’))
…
3
STATIC METHODS
static methods (class methods)
special methods that pertain to the class… not to a specific object
are called through the name of the class… not through an object
System.out.print(Math.max(3, 10));
System.out.print(Math.sqrt(9));
System.out.print(Math.random());
non-static methods (instance methods)
methods that pertain to a specific object
are called through the name of a specific object
Random gen = new Random();
int num1 = gen.nextInt();
calling object
String aNoun = "Mary";
String aVerb = "eats";
if (aNoun.length() > 10)
…
System.out.print(aVerb.charAt(3));
Output
s
4
CALLING METHODS
int big;
big = Math.max(3, 10);
System.out.print(Math.max(100,200));
int someInt = 10;
if (Math.sqrt(3+6) < Math.min(someInt,20))
System.out.print("true");
// max of 10, 20, and 15
System.out.print(_______________________);
Output
"Max of 10, 20, 15 = " + Math.max(10,
Math.max(20, 15))
String s = "Hello";
System.out.print(s.length());
Output
if (s.charAt(0) == 'H')
System.out.print("true");
true
// display last character of s
System.out.print(_________________);
"Last character of s [s.charAt(0)] = " + s.charAt(4)
Output
5
STATIC METHODS
note that main is a static method…
 it is invoked by the system without creating an object
instance (non-static) variables do not exist until an object exists…
but static methods can be called even if no object exist…
so static methods…
 do not have access to non-static variables and methods
 have access to static variables and methods
ex: main can only call static methods…
static methods are called through the name of the class (or even through an object)
can static methods use the this reference?
 this is used to refer to the parent object of a variable or method.
 When you declare static on a method, the method can be called without
needing to instantiate an object of the class.
 Therefore the this keyword is not allowed because your static method is not
associated with any objects
6
STATIC VARIABLES
with non-static variables:
each object has its own copy of the variable
with static variables:
only one copy of the variable exists to be shared by all objects of the class
public class someClass {
private static int a;
private int b;
private boolean c;
…
object1
object2
}
b
c
b
c
a
memory space is created when the class in which it is declared is loaded
All objects of the class can read and change a static variable
useful to share info among objects of the same class
ex: constants, nb of objects created, …
7
STATIC VARIABLES
can be initialized in the declaration
if not explicitly initialized, it is automatically initialized to false / zero /
null
space and initial value is assigned:
when the class is loaded for the 1st time
not every time an object is created
public class SomeClass {
private static int a = 10;
private static int b;
…
}
constants are good candidates for being static variables
public static final int nbDays = 365;
a static method:
cannot access an instance variable,
can access a static variable
8
JUST CHECKING …
A static method is one that can be used with ___________.
A.
B.
C.
D.
an instance variable
a local variable
a global variable
the class name as a calling object
Output
D
9
JUST CHECKING …
Only ______ copy/copies of a static variable are available to
objects of a class.
A.
B.
C.
D.
E.
zero
one
two
three
none of the above
Output
B
10
EXAMPLE
Output
public class Account {
private static int nbAccounts=0;
private int balance;
Syntax error
public Account() {
nbAccounts++;
balance = 0;
}
public static int getNbAccounts(){
return nbAccounts; // OK
}
public static int getBalance(){
return balance; // OK ? No because is declared as static
}
}
Account.java
System.out.print(Account.getNbAccounts());
Account myAccount = new Account();
System.out.print(myAccount.getNbAccounts());
Driver
Output
Without static at the
method “getBalance()”,
the result will be:
0 1
11
EXAMPLE
public class Account
{
public static int nbAccounts=0;
public int balance;
}
public Account() {
nbAccounts++;
balance = 0;
}
Output
A.
B.
Account.java
C.
Account a = new Account();
System.out.println(a.balance + " " + a.nbAccounts);
Account b = new Account();
System.out.println(a.balance + " " + a.nbAccounts);
System.out.println(b.balance + " " + b.nbAccounts);
Driver
D.
E.
0 0
0 0
0 0
0 1
0 2
0 3
0 1
0 2
0 2
0 2
0 2
0 2
Syntax error
12
THE FAMOUS SYSTEM.OUT.PRINT
System
out
--> an object of the class PrintStream (in java.io)
PrintStream
--> a static variable in the class System
System.out
--> a standard Java class in the package java.lang
--> has an instance method called print
so System.out.print calls the print method of the
PrintStream class through the object System.out (the
class variable of the class System)
13
EXAMPLE: JAVA.LANG.MATH
java.lang.Math
 declares methods and math constants
 constants: Math.PI, Math.E
 methods: max(),min(),abs(),random(),sqrt(),…
 all methods are static
Math.E
Math.random()
Math.max(3, 10)
Math.sqrt(9)
Class
Package
Math
java.lang
int radius;
double area, circumference;
System.out.print("Enter the circle's radius: ");
radius = keyboard.nextInt();
area = Math.PI * Math.pow(radius, 2);
circumference = 2 * Math.PI * radius;
14
JUST CHECKING …
All of these are methods of Java’s Math class except:
A.
B.
C.
D.
E.
pow
min
random
toString
sqrt
Output
toString()
15
2- WRAPPER CLASSES
A wrapper class is an “container” to a primitive type
so we “wrap” the primitive time by some class
int x = 20;
// primitive type
Integer y = new Integer(20); // reference type
y
x
20
2000
20
2000
16
WRAPPER CLASSES
Every primitive type has a corresponding wrapper class in the
java.lang package
Primitive Type
Wrapper Class
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
char
Character
boolean
Boolean
void
Void
Wrapper classes also contain a number of useful predefined
constants and static methods
17
WRAPPER CLASSES
used for what?
wrapper classes contain:
many useful methods to help manage the associated type
ex: to convert an integer stored in a String to an int value:
String s = "2003";
int num = Integer.parseInt(str);
let's visit the Sun Java API, to see:
some methods and constants of the Integer class
some methods and constants of the Character class
some methods and constants of the Boolean class
…
18
SOME METHODS IN WRAPPER CLASSES
methods to convert a string representation of a number to the
number
 Integer.parseInt, Long.parseLong,
Float.parseFloat, and Double.parseDouble
String s1;
s1 = keyboard.next();
double number1 = Double.parseDouble(s1);
toString() methods to convert from a numeric value to a
string representation of the value
Double.toString(123.99);
returns the string value "123.99"
19
BOXING AND UNBOXING
Boxing:
converting a primitive value to an object of its wrapper class
Integer integerObject = new Integer(42);
Unboxing:
converting an object of a wrapper class to the corresponding
value of a primitive type
use the "typeValue()" methods…
int i = integerObject.intValue();
double d = doubleObject.doubleValue();
char c = charObject.charValue();
…
20
AUTOMATIC BOXING AND UNBOXING
since Java 5.0, we have automatic boxing and unboxing
Automatic boxing:
Instead of creating a wrapper class object (as shown before)
Integer integerObject = new Integer(42);
we can use a automatic type cast:
Integer integerObject = 42;
Automatic unboxing:
Instead of having to invoke the a method
int i = integerObject.intValue();
the primitive value can be recovered automatically
int i = integerObject;
21
JUST CHECKING …
All of the following are wrapper classes except:
A.
B.
C.
D.
E.
String
Integer
Character
Double
Boolean
Output
String
22
3. REFERENCES
a variable can be
primitive type
reference to an object
an object ≠ a reference to an object
reference=
Object
holds the memory address of an object
can be seen as a “pointer” to an object
Account myAccount;
myAccount = new Account();
Reference
myAccount
2000
2000
if a reference R contains the address of an object O
then we say that R points to O
23
2 SPECIAL REFERENCES
null reference
this reference
24
A NULL REFERENCE
A reference that currently points to no object
Account myAccount;
myAccount = new Account();
myAccount
myAccount
4000
4000
String myName;
myName = new String("hello");
25
ACCESSING A NULL REFERENCE
be careful: a null reference points to no object so we cannot access its
attributes or methods (cannot use the dot notation)
Account myAccount;
myAccount = new Account();
myAccount.deposit(100); // OK
Account yourAccount;
yourAccount.deposit(100); // OK?? No. We have to initialize the variable yourAccount
String myName;
System.out.print(myName.length());// OK?? The variable myName may not have been
initialized
26
ACCESSING A NULL REFERENCE
be careful: a null reference points to no object so do not use the dot
notation
public class AccountNo2 {
private double balance;
public Account otherAccount;
public AccountNo2() {
balance = 0;
}
}
AccountNo2 acc = new AccountNo2();
acc.otherAccount.deposit(100); // No Syntax errors but in displaying
object ″acc″, the null pointer exception occurs because the object
″acc″ points to another object ″otherAccount″. This is cannot be used.
AccountNo2 otherAccount = new AccountNo2();
otherAccount.deposit(100); // OK
27
CHECKING FOR NULL REFERENCES
To avoid an error, we can check for null reference before accessing an
object
if (anAccount!= null)
anAccount.deposit(100);
can assign null to a reference
anAccount
Account anAccount = new Account();
anAccount = null;
4000
4000
anAccount
28
JUST CHECKING …
null can be used:
A. to indicate a variable has no real value
B. in a Boolean expression with == or !=
C. as a placeholder
D. all of the above
E. none of the above
Output
A
29
THE THIS REFERENCE
The this reference
allows an object to refer to itself
is a reference to the current object
i.e. inside a method, this refers to the object through which the
method is being executed
public void deposit(int amount)
{
balance += amount;
this.balance += amount;
}
myAccount.deposit(100);
// "this" refers to ??
yourAccount.deposit(200); // "this" refers to ??
30
REFERENCE ASSIGNMENT
The act of assignment takes a copy of a value and
stores it in a variable
For primitive types:
num2 = num1;
Before
After
num1
num2
num1
num2
5
12
5
5
31
REFERENCE ASSIGNMENT
For references, assignment copies the memory location
Account myAccount = new Account();
Account yourAccount = new Account();
yourAccount = myAccount;
Before
myAccount
2000
yourAccount
3000
After
myAccount
2000
yourAccount
2000
and guess what… you have just lost access to
if 2 references “point” to the same objects, they are aliases of each
other
32
REFERENCE ASSIGNMENT
Same with strings… because strings are objects
String word1 = “hello”;
String word2 = “mary”;
word1 = word2;
word1
Before
word2
“hello”
word1
“mary”
“hello”
After
word2
“mary”
33
EQUALITY OF REFERENCES
The == operator:
compares equality of references
returns true if the references are aliases of each other
ie if they point to the same object
NOT if the objects pointed have the same content
Account myAccount = new Account("ted", 123, 100);
Account yourAccount = new Account("ted", 123, 100);
yourAccount
myAccount
4000
"ted"
4000
8000
"ted" 8000
123
123
100
100
if (myAccount == yourAccount)
// true or false?
System.out.print("the same");
34
EQUALITY OF OBJECTS
The method equals :
is defined for all objects
but unless we redefine it in our class, it has the same semantics as the == operator
we can redefine it to return true under whatever conditions we think are
appropriate (ex. equality of content, not address)
public class Account {
private String name;
private double balance;
private int acctNumber;
boolean equals(Account anotherAccount) {
return (this.name == anotherAccount.name &&
this.balance == antherAccount.balance &&
this.acctNumber == anotherAccount.acctNumber);
}
…
if (myAccount.equals(yourAccount))
System.out.print("same content");
if (myAccount == yourAccount)
System.out.print("same object");
35
GARBAGE COLLECTION
When an object no longer has any references to it, it can no longer be accessed by
the program!
myAccount yourAccount
Java has an automatic garbage collector
runs periodically
returns memory of inaccessible objects to the system for future use
If a reference is no more useful… assign it to null (myRef=null;), so that the
garbage collector can pick it up
In other languages, the programmer is responsible for performing garbage
collection
36
PASS BY VALUE VS PASS BY REFERENCE
pass by value
all primitive types are always passed by value
the formal parameter is a copy of the actual parameter
the method modifies the copy
but the actual parameter is never modified
pass by reference
object parameters are always passed by reference
the actual parameter and the formal parameter become aliases of
each other
the method can modify the actual parameters
we copy the reference; not the object
37
EXAMPLE: SWAPPING 2 INT
public class PassDriver
{
public static void main(String[] arg)
{
int x = 10;
int y = 20;
System.out.println("1 " + x + " " + y);
swap(x, y);
System.out.println("4 " + x + " " + y);
}
Output
1
2
3
4
10
10
20
10
20
20
10
20
public static void swap(int param1, int param2)
{
System.out.println("2 " + param1 + " " +
param2);
int temp = param1;
param1 = param2;
param2 = temp;
System.out.println("3 " + param1 + " " +
param2);
}
}
38
EXAMPLE: SWAPPING 2 INTEGER
public class PassDriver
{
public static void main(String[] arg)
{
Integer x = 10;
Integer y = 20;
System.out.println("1 " + x + " " + y);
swap(x, y);
System.out.println("4 " + x + " " + y);
}
Output
1
2
3
4
10
10
20
10
20
20
10
20
public static void swap(Integer param1, Integer param2)
{
System.out.println("2 " + param1 + " " + param2);
Integer temp = param1;
param1 = param2;
param2 = temp;
System.out.println("3 " + param1 + " " + param2);
}
}
39
EXAMPLE: SWAPPING 2 MYINT
PassDriver.java
public class PassDriver {
public static void main(String[] arg) {
MyInt a = new MyInt(10);
MyInt b = new MyInt(20);
System.out.println("1 " + a.getValue() + " " + b.getValue());
swap(a, b);
System.out.println("4 " + a.getValue() + " " + b.getValue());
}
public static void swap(MyInt param1, MyInt param2)
{
System.out.println("2 " + param1.getValue() + " " + param2.getValue());
MyInt tmp = new MyInt(param1.getValue());
param1.setValue(param2.getValue());
param2.setValue(tmp.getValue());
System.out.println("3 " + param1.getValue() + " " + param2.getValue());
}
Output
1
2
3
4
10
10
20
20
20
20
10
10
}
public class MyInt {
private int value;
public MyInt(int data) { this.value = data; }
public void setValue(int data) { this.value = data; }
public int getValue() { return value; }
}
MyInt.java
40
CONCLUSION
if argument is a primitive type:
A
method cannot change the value of the argument
if argument is a reference:
A
method can change the value of the argument
41
EXAMPLE 1: SWAPPING 2 ACCOUNT
public static void main(String[] arg)
{
Account a = new Account("ted", 123, 100);
Account b = new Account("mary", 456, 99);
System.out.println(a + " " + b);
swap(a, b);
System.out.println(a + " " + b);
}
public static void swap(Account a1, Account a2)
{
Account tmp;
tmp = a1;
a1 = a2;
a2 = tmp;
}
Output
Account@15db9742 AccountNo3@6d06d69c
Account@15db9742 AccountNo3@6d06d69c
42
EXAMPLE 2: SWAPPING 2 ACCOUNT
public static void main(String[] arg)
{
Account a = new Account("ted", 123, 100);
Account b = new Account("mary", 456, 99);
System.out.println(a + " " + b);
swap(a, b);
System.out.println(a + " " + b);
}
public void swap(Account a, Account b)
{
Account tmp = a;
a.changeTo(b);
b.changeTo(tmp);
}
public class Account {
…
public void changeTo(Account b) {
this.acctNumber = b.acctNumber;
this.balance = b.balance;
this.name = (b.name).substring(0);
}
public String toString(){
return ("Name : " + name + " Account Number :
" + numAccount + " The new balance after
deposit = " + balance);
}
Driver
Account.java
Output
By adding the method “toString()” in the class Account, we obtain, after
swapping, this result
Name : Mary Account Number : 456 The new balance after deposit = 99.0
Name : Mary Account Number : 456 The new balance after deposit = 99.0
43
ANONYMOUS OBJECTS
The new operator
calls a constructor which initializes an object,
returns a reference to the location in memory of the object created
if the object created will only be used as an argument to a method, and never
used again, no need to assign it to a variable
create & use on the fly!
ex:
BankAccount temp = new BankAccount("mary", 100);
if (someObject.equals(temp)
System.out.print("equal");
if (someObject.equals(new BankAccount("mary", 100))
System.out.print("equal");
44
USING AND MISUSING REFERENCES
it is very important to insure that private instance variables
remain truly private
If an instance variable is:
a primitive type, just make it private
a class type, private may not be enough …
public class Person
{
private String name;
private java.util.Date born;
private java.util.Date died;
…
}
45
CONSTRUCTOR FOR CLASS PERSON
public Person(String initialName, Date birthDate, Date deathDate)
{
if (consistent(birthDate, deathDate))
{
name = initialName;
born = new Date(birthDate); // why not just born = birthDate??
if (deathDate == null)
died = null;
else
died = new Date(deathDate); // why not just born = deathDate??
}
else
System.exit(0);
}
Date birth = new Date("April", 1, 1970);
Person original = new Person("john", birth, null);
birth.setMonth("January");
46
COPY CONSTRUCTORS
A copy constructor:
a constructor with only 1 argument of the same type as the class
should create a different object that is copy of the argument
47
COPY CONSTRUCTOR
for instance variables that are primitive types
public Date(Date aDate) {
if (aDate == null) System.exit(0); //Not a real date.
month = aDate.month; // a string
day = aDate.day;
// an int
year = aDate.year;
// an int
}
for instance variables that are class types
public Person(Person original) {
if (original == null) System.exit(0);
name = original.name;
// a string
born = new Date(original.born); // a reference to a class
if (original.died == null)
died = null;
else
died = new Date(original.died); // a reference to a class
}
48
JUST CHECKING …
A copy constructor has _________ parameters.
A. zero
B. one
Output
B
C. two
D. Three
E. How ever many one needs
49
MUTABLE AND IMMUTABLE CLASSES
immutable class
A class that contains no methods (other than constructors) that change
the data in an object of the class
It is safe to return a reference to an immutable object
because the object cannot be changed
ex: the String class
mutable class
A class that contains public methods that can change the data in its
objects
Never write a method that returns a mutable object
Instead, use a copy constructor
50
PRIVACY LEAKS AGAIN…
incorrectly defined mutator or accessor methods
ex:
public Date getBirthDate()
{
return born; //dangerous
return new Date(born); //correct
}
OK for Strings
51
DEEP COPY VERSUS SHALLOW COPY
A deep copy of an object:
a copy that has no references in common with the original
Exception: References to immutable objects are allowed to be
shared
a shallow copy of an object:
can cause dangerous privacy leaks in a program
52
JUST CHECKING …
A condition that allows a programmer to circumvent the private
modifier and change the private instance variable is called:
A.
B.
C.
D.
a copy constructor
a privacy leak
a class invariant
an anonymous object
Output
A
53
6. JAVADOC (WILL BE COVERED IN TUTORIAL)
Comments in Java
// Can be single line comments
/* More than one line.
Useful to "erase" a block
of code from compilation */
/**
* A Javadoc comment
* To generate nice HTML documentation
*/
54
WHAT IS JAVADOC?
A standard for documenting Java programs
javadoc.exe
For each X.java, it will create an X.html
generates documentation of your Java classes in a standard format
comes with the JDK.
plus a couple of additional pages (index, ..)
ex: If you wrote MyClass.java
then running “javadoc MyClass.java”
generates a file “MyClass.html”
that contains properly formatted comments
55
56
The output from Javadoc looks exactly like the API
documentation… since that's the way it was generated!
57
GENERAL FORM OF A JAVADOC COMMENT
/**
*
*
*
*
*
*
*
*
*
*
One sentence ending with a period describing the purpose.
Additional lines giving
more details (html tags can be included)
javadoc tags to specify more specific information,
such as parameters and return values for a method
@Tag Description ...
@Tag Description ...
*/
58
TAGS
Allow you to specify specific information used in the HTML file
most common tags:
For files, classes and interfaces:
@author Name
@version Version number
For methods:
@param name description
@return description
@exception exceptionClass description
@deprecated description
For everything:
@see relatedReference (ex. other class name)
59
DOCUMENTING FILES, CLASSES AND INTERFACES
Javadoc comments go immediately before the class or
interface (or top of file)
ex:
/**
* A coin value and its name.
* @author YourNsmr
* @version 1.1
* @see JavadocForger
*/
public class JavadocCoin {
…
}
javadoc -author -version Javadoc.java
60
61
DOCUMENTING METHODS
Javadoc comments go immediately before the method definition
Common tags :
@param <name of parameter> <description>
@return <description>
ex:
/**
* This method does this.
* @param coinValue Initial coin value
* @param coinName Initial coin name
* @return The value of the coin
*/
public double someMethod(double coinValue, String coinName){
…
}
62
63
JAVADOC
can add Html tags to the comments to add nicer
formatting to the resulting document.
Advantages:
looks very nice…
provides a consistent look and feel to API documents
when source code is changed:
the Javadoc comments can be changed in the source, at the same
time.
 the external documentation is then easily re-generated.
64