



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Based on a handout by Patrick Young.
class AnExample extends ConsoleProgram {
public void methodOne { int a = readInt("Enter a: "); println("a = " + a); }
public void methodTwo { int b = a; // BUG!: cannot refer to variable a in methodOne println("b = " + b); } }
class AnExample extends ConsoleProgram {
public void methodThree { int a = 4;
for (int i = 0; i < 5; i++) { int b = a; // this is okay
if (a > b) { // okay to access a and b here int c = 3;
println(i); // okay to access i here println(b); // okay to access b here println(c); // okay to access c here }
println(c); // illegal: c is no longer in scope here }
println(a); // okay to access a here println(b); // illegal: b is only in scope in body of for loop println(i); // illegal: i is only in scope in body of for loop } }
class Thing { public Thing() { x = 0; }
/* Public instance variable */ public int x
/* Public class variable */ public static int y }
class MainProgram extends ConsoleProgram {
public void run() { Thing th1 = new Thing(); Thing th2 = new Thing(); Thing th3 = new Thing();
// NOTE: we can access a public class variable directly via // the class name (see below). Thing.y = 7;
// We can also access a public class variable by any object // of that class. th1.y = 8; th2.y = 17; th3.y = 18;
println(Thing.y); println(th1.y); println(th2.y); println(th3.y); } }
Thing.y = 7;
Thing th1 = new Thing(); th1.y = 7;
Thing th1 = new Thing(); Thing.y = 7;