I've recently picked up Java after using a "gimmick" programming language called GML ( Game Maker Language ). I've read a lot of tutorials and even a Java for Dummies *.pdf book. The basics are similar to what I'm accustomed to but there's still some confusion.
I'm currently playing around with how the static, public, protected etc things work and I stumbled upon a problem.
In the following copypasted code ( a tutorial I slightly modified ) the problem occurs inside the main(Strings args[]) thingy near the end.
Expand|Select|Wrap|Line Numbers
- public class ThisPointerExample {
- public static void main(String[] args) {
- HumanBeing me = new HumanBeing("Brown");
- while(true)
- {
- HumanBeing your = new HumanBeing("Blue"); /* *** noteworthy line *** */
- break;
- }
- System.out.println(me.isEqual(your)); /* *** problem is here with "your" It seems the variable "your" is not declared - that's what the error says anyways. I would have thought it woul be declared inside the while() loop *** */
- }
- }
- class HumanBeing {
- private String eyeColor;
- public HumanBeing(String color) {
- this.eyeColor = color;
- }
- public String getEyeColor() {
- return eyeColor;
- }
- public boolean isEqual(HumanBeing your) {
- return this.eyeColor.equals(your.getEyeColor());
- }
- }
Here are some of my thoughts:
1. A variable declared inside a loop will be discarded after the loop ends and the memory of this variable is freed because the variable is local to the loop and not the class.
2. However, adding a "this." inside the variable declaration doesn't fix this problem. I'm thinking this would tell java to store the variable with the class and not the loop - why doesn't this work? And what would be the proper way to declare a variable to a class inside a loop?
Thanks in advance.
- Jon