Download Lab06 - Marquette University

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
J A V A
L A B
M A N U A L
LAB
OBJECT ORIENTED PROGRAMMING IN JAVA
6
Reinforcing the Concepts of
Modifiers, Scope, Equali t y and
References
PURPOSE
This lab has three pre-written programs that you will run to reinforce the concepts of
6.1 Access modifiers, static and the scope of variables in ScopeTest.java
6.2 Equality of primitives and equality of objects in Equals.java
6.3 Passing variable arguments to methods in PassingValues.java
In addition, you will practice drawing state of memory diagrams.
TO PREPARE

Read Wu: Chapter 4

Read through this laboratory session

Using your memory device, create a directory called lab6 and copy the three files ScopeTest.java,
Equals.java, PassingValues.java from http://www.mscs.mu.edu/~marian/60/Labs/lab06/ .
TO COMPLETE

This is an individual lab. You may ask the lab tutor for help and you may consult with your
neighbor if you are having difficulties.

When you have completed the lab, your grade for the lab will be determined by your presence in the
lab.
MARIAN MANYO, MARQUETTE UNIVERSITY
PAGE 6.1
6.1 Scope of variables
Data Members or Data Fields
1. Data members are declared inside the class and outside of any method.
2. Data members are constants if they are modified by final , and variables, otherwise.
3. If a data member is modified by static, it belongs to the class. There is only one version of a class
data member and it is shared by all objects of this type.
4. If a data member is not modified by static, it is an instance data member. Each object of this type
has its own version of an instance data member.
5. Data members are modified by access modifiers. So far we have used the public and private
access modifiers. Additional access modifiers are protected and to use no modifier. These
modifiers determine which outside classes have access to the data members. A complete
explanation of this topic will be given at the end of this course or the beginning of the next course.
6. Instance methods have access to all to both class or instance data fields. Class methods, those that
are modified by static , may only access class data members. This makes sense, since class methods
can be invoked on the class, whereas instance methods may only be invoked on an object.
Local Variables
1. Local variables are declared inside methods and include a method's formal parameters.
2. A formal parameter is known throughout the body of the method.
3. A local variable declared inside the body of a method is known from the point at which it is
declared to the end of the block in which it is declared.
4. Local variables are never modified by the access modifiers since they may only be accessed in the
method. They also are never modified by static .
P r o g r a m : Open the program ScopeTest.java.
A class defines a data type. In Lab 05, once the Rectangle class was defined, variables of type Rectangle
could be declared. The code below defines a data type called Scope . This is used for illustration purposes
only, the actual purpose of this class is immaterial. Read the code for understanding and then answer the
questions that follow.
class Scope
{
private static int one = 1;
private int two;
public int three;
public static final int FOUR = 4;
public Scope(int w, int x)
{
//++ is the auto-increment operator and adds one onto the value
one++;
two = w;
three = x;
}
public void change(int x)
{
int y = one + x;
two = one * y;
three = three * FOUR;
}
PAGE 6.2
MARIAN MANYO, MARQUETTE UNIVERSITY
J A V A
L A B
M A N U A L
public String toString()
{
return (" one = " + one + " two = " + two + " three = " + three);
}
}
There are six variables or constants defined in the class Scope and each of these may either be instance,
class or local data. Classify each, there are six possibilities.
one
____________________________________________________________________________________________
two
____________________________________________________________________________________________
three ____________________________________________________________________________________________
FOUR ____________________________________________________________________________________________
w ________________________________________________________________________________________________
x ________________________________________________________________________________________________
y ________________________________________________________________________________________________
Check your answers with someone else in class, or with the lab
tutor. If you do not agree, correct your answer and be sure that you
understand the concept.
Scope class
Fill in this drawing to agree with you answers to the above.
Draw a diagram of the Scope class and a Scope object.
The Scope class should store the shared class data members.
The Scope object should store the instance data members that
are unique to each Scope object
Scope object
The local variables in any method do not belong to the class or the
object.
To use the class Scope , there is a driver class defined in the file ScopeTest.java , which is called
ScopeTest . You may put more than one class definition in a file. Compiling the file will result in more
than one .class file being created. Since Scope is only a demonstration class, this is what I have chosen to
do. Some of the statements in the main method have been commented out and should remain so when you
compile the program. Later, we will uncomment some of these statements. For now we have
class ScopeTest
{
public static void main(String[] args)
{
Scope a = new Scope(3, 5);
System.out.println("1. a: " + a);
a.change(2);
System.out.println("2. a: " + a);
}
}
MARIAN MANYO, MARQUETTE UNIVERSITY
PAGE 6.3
S t e p 1 : Predict the output of the code.
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
Compile the file ScopeTest.java and run the application ScopeTest . Compare the results to your
prediction, making corrections where needed. Be sure that you understand the concepts.
S t e p 2 : After each statement below, state whether the code will compile or will not compile. If it will not
compile, explain why. For each statement that compiles, comment on whether or not it violates the concept
of encapsulation. If you add any of these statements to the application to check your answers, be sure to
remove them before proceeding. Check your answers with someone else in class.
System.out.println(a.two); _______________________________________________________
__________________________________________________________________________________
System.out.println(Scope.three);__________________________________________________
__________________________________________________________________________________
System.out.println(a.FOUR); ______________________________________________________
__________________________________________________________________________________
Scope.FOUR = 5; __________________________________________________________________
__________________________________________________________________________________
a.three = 3; _____________________________________________________________________
__________________________________________________________________________________
S t e p 3 : In the class Scope and at the beginning of the method public void change(int x) add the
statements
int x = 10;
w = 5;
Compile the code and record the essence of the compiler error messages. Explain
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
Essentially, two local variables in a method can not have the same name. Can two local variables in
different methods have the same name? Substantiate your answer using the code in the class Scope .
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
PAGE 6.4
MARIAN MANYO, MARQUETTE UNIVERSITY
J A V A
L A B
M A N U A L
S t e p 4 : Now, eliminate the two statements added in Step 3. In the constructor in the class Scope ,
modify the statement
two = w;
to
int two = w;
Compile the file and run the application. Record what is printed?
_____________________________________________________________________________________________
_____________________________________________________________________________________________
The above is a common error made by new programmers. Java allows a local variable to have the same
name as a data member. Thus, the statement int two = w; declares a local variable, two, with the same
name as a data member. Therefore, statement assigns the value w to the local variable two , not to the
data member two . Any data member that is not assigned a value in the constructor is assigned the
equivalent of zero. The equivalent of zero is 0 or 0.0 if the data type is a primitive integer, floating-point
number or character, is false if the data type is boolean and is null if the data type is a class type.
Inside of a method, is it possible to distinguish between a data member and a local variable with the same
name. The answer is YES. The Java reserved this refers to the current object on which a method is
invoked. Inside of a method, the word this may be dotted with the name of a data member or method
member to refer to the current object's data member or invoke the method on the current method. Rewrite
the constructor in Scope as shown below.
public Scope(int two, int three)
{
one++;
this.two = two;
this.three = three;
}
S t e p 5 : Currently, a state of memory diagram for the application is:
Scope.one
1 2
Scope.FOUR
4
Scope
a
two
three
3 12
5 20
Uncomment the next three statements in the application class ScopeTest.java and modify the state of
memory diagram to show the effect of this added code.
Scope b = new Scope(7, 8);
System.out.println("\n3. a: " + a);
System.out.println("4. b: " + b);
MARIAN MANYO, MARQUETTE UNIVERSITY
PAGE 6.5
Predict the output of the two print statements.
_____________________________________________________________________________________________
_____________________________________________________________________________________________
Compile the file ScopeTest.java and run the application ScopeTest . Compare the results to your
prediction, making corrections where needed. Be sure that you understand the concepts.
S t e p 6 : Uncomment the last four lines in the application ScopeTest.java . Redraw the state of memory
diagram showing the result of these four lines.
a = b;
a.change(2);
System.out.println("\n5. a: " + a);
System.out.println("6. b: " + b);
Predict the output of the two new print statements.
_____________________________________________________________________________________________
_____________________________________________________________________________________________
Compile the file ScopeTest.java and run the application ScopeTest . Compare the results to your
prediction, making corrections where needed. Be sure that you understand the concepts. Discuss these
results with your neighbor. THIS IS IMPORTANT.
PAGE 6.6
MARIAN MANYO, MARQUETTE UNIVERSITY
J A V A
L A B
M A N U A L
6.2 CHECKING FOR EQUALITY
To check for the equality of two values, the relational operator == is used. Therefore, if
int
x = 5;
then the expression x == 5 has a value of true
and the expression x == 6 has a value of false .
Program:
Open the file Equals.java
class Equals
{
public static void main(String[] args)
{
int x = 5, y = 5, z = 6;
System.out.println("x is " + x + "
y is " + y + "
System.out.println("x == y is " + (x == y));
System.out.println("x == z is " + (x == z));
z is " + z);
String r = new String("Help");
String s = new String("Help");
String t = new String("HELP");
System.out.println("\nr is " + r + "
s is " + s + "
System.out.println("r == s is " + (r == s));
System.out.println("r == t is " + (r == t));
t is " + t);
}
}
S t e p 1 : Compile and run the program. Record the results.
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
All of the primitive types are store d by va lue . That is, the value assigned to the variable is stored in the
bytes that are reserved when the variable is declared.
All objects are sto red by refer ence . That is , the address of the object assigned to the variable is stored
in the bytes that are reserved when the variable is declared.
A memory diagram for the code above is
x
5
y
5
z
6
r
s
"Help
"
MARIAN MANYO, MARQUETTE UNIVERSITY
"Help"
t
"HELP"
PAGE 6.7
Use this diagram to explain why r == s, which compares the values stored in r and s, is false .
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
S t e p 2 : To compare two objects for equality, the object must have a method called equals . Add these
statements to the main method.
System.out.println(" r.equals(s) is " + r.equals(s));
System.out.println(" r.equals(t) is " + r.equals(t));
Compile and run the program. Record what is printed by this new line of code.
_____________________________________________________________________________________________
_____________________________________________________________________________________________
Where is the equals method defined? The method
public boolean equals(Object obj)
is defined in the String class. Notice that any object may be passed to the method. Obviously, if obj is not
a String , false is returned. If obj is a String that is identical to this String , true is returned. Otherwise,
false is returned.
S t e p 3 : The String class has another method that compares this String to obj ignoring the case of the
letters.
public boolean equalsIgnoreCase(Object obj)
To the main method, add two statements that print the values returned when r is compared to s and t
using the equals method and the equalsIgnoreCase method. Record the lines you added.
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
Compile and run the program. Record what is printed by the two new statements.
_____________________________________________________________________________________________
_____________________________________________________________________________________________
PAGE 6.8
MARIAN MANYO, MARQUETTE UNIVERSITY
J A V A
L A B
M A N U A L
6.3 PASSING VARIABLES TO METHODS
In Java, we say variables are passed to methods by value. That is, all variables are passed to methods by
copying the value stored in the argument to the parameter.
If the variable's type is a primitive, the value passed is the primitive value. If the variable's type is a class
type, the value stored in the variable is a reference. Therefore, to make this important distinction, we
rephrase "Variables are passed by value." as "Primitives are passed by value and objects are passed by
reference."
Program:
Open the file PassingValues.java
This file contains two classes: Number, a utility class and PassingValues , the driver class.
S t e p 1 : Read the class Number for understanding.
Draw a picture of a Number object
class Number
{
private int value;
public Number(int v)
{
value = v;
}
public void setValue(int v)
{
value = v;
}
public String toString()
{
return "" + value;
}
}
Now follow this partial code that uses a Number object. Draw a state of memory diagram for this partial
code.
Number num = new Number(6);
System.out.println(num);
num.setValue(15);
System.out.println(num);
What is printed by this partial code?
_____________________________________________________________________________________________
S t e p 2 : Now read the actual program, which is stored in the PassingValues class. The program defines
two methods
public static void main(String[] args
and
public static void makeChanges(int n, Number num )
When the program is run, it starts with the main method. Inside the class method main the second class
method makeChanges is called in the statement
makeChanges(n, num);
MARIAN MANYO, MARQUETTE UNIVERSITY
PAGE 6.9
class PassingValues
{
public static void main(String[] args)
{
int n = 5;
Number num = new Number(10);
System.out.println(
"In main before change:
n is " + n + "
num is " + num);
System.out.println(
"\nIn main after change : n is " + n + "
num is " + num);
makeChanges(n, num);
}
public static void makeChanges(int n, Number num )
{
System.out.println(
"\nIn makeChanges before: n is " + n + "
num is " + num);
n = n + 2;
num.setValue(12);
System.out.println(
"In makeChanges after :
n is " + n + "
num is " + num);
}
}
Predict the output by completing the state of memory diagram. Note that the method main has two local
variables n and num . makeChanges has two parameters, which are local variables, also named n and
num. When the main method calls makeChanges, the execution of main is interrupted and
makeChanges is executed. When the execution of makeChanges is completed, the execution of main
continues.
main
makeChanges
n
n
num
num
In main before change:
n is ________
num is _________
In makeChanges before: n is ________
num is _________
In makeChanges after :
n is ________
num is _________
In main after change :
n is ________
num is _________
PAGE 6.10
MARIAN MANYO, MARQUETTE UNIVERSITY
J A V A
L A B
M A N U A L
Now, compile and run the program. Check your predicted answers. If you were not correct, discuss this
program with your neighbor. Be sure that you understand what is occurring. Also, be sure that you can
correctly draw the state of memory diagram.
S t e p 3 : Will the results change if the parameters in the makeChanges method are changed? Change the
names of the parameters in the method makeChanges to int a and Number b.
public static void makeChanges(int a, Number b )
{
System.out.println(
"\nIn makeChanges before: a is " + a + "
b is " + b);
a = a + 2;
b.setValue(12);
System.out.println(
"In makeChanges after :
a is " + a + "
b is " + b);
}
Compile and run the program. Record the results
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
What relationship do the parameter names have to the argument names?
_____________________________________________________________________________________________
_____________________________________________________________________________________________
When a Java program is executed, or run, the Java Virtual Machine invokes the main method on the name
of the driver class. This is why main must be modified by static. A static method only has access to the
class's static data and static methods, i.e. a static method does not have access to instance data or
instance methods. This is why the makeChanges method must also be static.
S t e p 4 : Change the header of the makeChanges method by removing the static modifier.
public void makeChanges(int a, Number b )
Compile the modified code. Record the compiler error message.
_____________________________________________________________________________________________
_____________________________________________________________________________________________
S t e p 5 : Remove the previous error by replacing the static modifier in the header of makeChanges.
Since makeChanges is a class method it should be invoked on the name of the class in which it is defined.
In the main method, replace the statement
makeChanges(n, num);
with the statement
PassingValues.makeChanges(n, num);
MARIAN MANYO, MARQUETTE UNIVERSITY
PAGE 6.11
Compile and run the program. Are there any differences in the way the program is run?
_____________________________________________________________________________________________
_____________________________________________________________________________________________
All methods must be invoked on the name of a class or on the name of an object. There are no exceptions.
When a static method is called from a static method without naming the class, it is implied that the
method being called is invoked on the same class as the calling method. Therefore, since the JVM executes
PassingValues.main(null);
in main the statement
changeValues(n, num);
i mp l ic itly calls a static method in the PassingValues class. Whereas, the statement
PassingValues.changeValues(n, Num)
exp l ic itly calls the method on the name of its class. Both statements are correct.
POST LAB EXERCISE
1. What is printed by the program Lab6A
cl
as
s
Nu
mb
er
{
in
t
va
lu
e;
cl
as
s
La
b6
A
{
pu
bl
ic
st
at
ic
vo
id
ma
in
(S
tr
in
g[
]
ar
gs
)
pu
bl
ic
st
at
ic
in
t
co
un
t
=
0; {
Nu
pu mb
bl er
PAGE 6.12
MARIAN MANYO, MARQUETTE UNIVERSITY
J A V A
ic
Nu
mb
er
(i
nt
v)
{
L A B
M A N U A L
a
=
ne
w
Nu
mb
er
(5
);
co
un Nu
t+ mb
+; er
b
va =
lu ne
e w
= Nu
v; mb
er
} (7
);
pu
bl
ic
bo
ol
ea
n
eq
ua
ls
(N
um
be
r
ot
he
r)
{
re
tu
rn
va
lu
e
==
ot
he
r.
va
lu
e;
Sy
st
em
.o
ut
.p
ri
nt
ln
(a
+
"
"
+
b)
;
Sy
st
em
.o
ut
.p
ri
nt
ln
(a
==
b)
;
MARIAN MANYO, MARQUETTE UNIVERSITY
PAGE 6.13
}
pu
bl
ic
St
ri
ng
to
St
ri
ng
()
{
re
tu
rn
""
+
va
lu
e;
}
pu
bl
ic
vo
id
ad
d(
Nu
mb
er
ot
he
r)
{
va
lu
e
=
va
lu
e
+
ot
he
r.
va
PAGE 6.14
MARIAN MANYO, MARQUETTE UNIVERSITY
J A V A
L A B
M A N U A L
lu
e;
}
}
System.out.println(a.equals(b));
a =
b;
b.s
etV
alu
e(9
);
Sys
tem
.ou
t.p
rin
tln
(a
+ "
" +
b);
Sys
tem
.ou
t.p
rin
tln
(a
==
b);
Sys
tem
.ou
t.p
rin
tln
(a.
equ
als
(b)
);
a =
new
Num
ber
(4)
;
MARIAN MANYO, MARQUETTE UNIVERSITY
PAGE 6.15
b =
new
Num
ber
(4)
;
Sys
tem
.ou
t.p
rin
tln
(a
+ "
" +
b);
Sys
tem
.ou
t.p
rin
tln
(a
==
b);
System.out.println(a.equals(b));
a.add(b);
System.out.println(a + " " + b);
System.out.println(Number.count);
}
}
PAGE 6.16
MARIAN MANYO, MARQUETTE UNIVERSITY