PDA

Click to See Complete Forum and Search --> : Very Simple Q! scope of variable


cantene
Mar 17th, 2001, 08:31 AM
Dear friends,

I feel a bit not confident about the scope of a variable and argument and wish to confirm with you.

Suppose I have the following fields and methods in my class:


public class BinaryCalculator extends JApplet implements ActionListener {
Number op1 = new Number();
Number op2 = new Number();

public String add(Number op1, Number op2) {
...
return op1 + op2
}

public String subtract(Number op1, Number op2) {
...
return op1 - op2
}

public void actionPerformed(ActionEvent e) {
try {
// Actions for Number keys
if (e.getActionCommand() == "1") {
op1 = 1
}
if (e.getActionComand() == "ADD") {
add("10","12")
}
...
}
}


In the above code, I use arguments of the same names as the outside fields op1, op2, will this
(1) cause error because the methods will modify the op1, op2 outside; or
(2) the op1, op2 in the methods (add, subtract) will simply treat them as local and can't see the outside op1, op2, thus no problem.

Also, if I declare in this way, what is the access modifier for op1 and op2, public or private?

If the .java file contains more than 1 class, is it only one of them can be public? Thanks

Thanks a lot.

Mar 17th, 2001, 02:39 PM
(1) No
(2) Yes it will treat them as local, but you can still access the "outside" members as you called them using the keyword "this".
this.op1
this.op2

The next one is tricky, so I hope I understand it correctly and also explain it correctly (in other words, check me on this one).
Declared in that way, the access modifier is considered "default" or "package scope" or "friendly". In my opinion, package scope is the best term because it reflects the fact that only subclasses belonging to the same package can access it. Note that there is no "friendly" keyword.

Yes, only one class can be declared public in a java source file which can contain multiple classes. The interesting thing here is that if you have a public class, the file must be named ThatPublicClassName.java. And the shocker is that non public classes don't need their source files to be named with the class name.