Tom Kelliher, CS 116
Oct. 16, 2000
Read 5.3--4.
Exam
Operators, expressions, and assignments.
Consider this example:
class Example { private int i = 1; public int k = 20; private static int l = 5; public void Method1() { int i = 2; i = 3; // Which i? // ... } private void Method2() { int j = 11; // ... { int i = 21; int j = 22; // ... } } }
Scope of instance variable (or method): entire class.
Scope of local variable: from point of declaration until end of enclosing block.
Identifier names must be unique within a particular scope level.
static
and final
.
A static
instance variable becomes a class variable --- it
is shared by all class objects. How is this different from an instance
variable?
Consider two Example
objects and their relationship to the instance
and class variables.
Applying final
to an identifier means that it can not be changed.
Example:
static final double PI = 3.14159;
We can control external access to class members.
What do you mean, external? What's a member? Class variables, instance variables, methods.
We're talking about methods accessing members.
Ways of distinguishing methods:
class Class1 { int i; void method1() { int j; i = 1; j = method2(i); } int method2(int a) { return a + 1; } }
// Class1 as before. class Class2 extends Class1 { void method3() { int k; i = 1; k = method2(12); } }The extension could be indirect.
// Class1 as before. public class applet extends Applet { Class1 class1Object = new Class1(); void method1() { class1Object.i = 12; class1Object.method1(); } }
Access is established by using access modifiers when declaring instance or
class variables: private
, protected
, public
.
No access modifier yields the default, package access.
By controlling access, we can practice information hiding, seen within the recurring concepts of levels of abstraction and security.
Only member functions of the member class have access.
Member functions of sub-classes do not have access.
Practice information hiding. All instance and class variables should be
private
. Think hard about what access to use with methods.
Any method has access.
i
and method1()
allowed?
class Class1 { private int i; public void method1() { i = 5; } private void method3() { method1(); } } class Class2 extends Class1 { private void method2() { i = 1; method1(); } } public class applet extends Applet { private Class1 object = new Class1(); public void init() { object.i = 12; object.method1(); } }
i
in this class?
class Class1 { int i = 1; // Call this i1. void method1() { int i = 2; // Call this i2. You get the idea. } void method2() { { int i = 3; } } void method3() { int i = 4; { int i = 5; } } }