In experimenting with the Dog program example, I learned that Java reads all the class definitions (variables, constructors, methods, etc.) before executing public static void main (String[] args). This means you can have the main program inside a class, and that the program will start with one copy of that particular class. This makes me wonder if you could refer to itself in an array.
class Dog {
public String name = "Ben";
public static void main (String[] args) {
Dog[] myDogs = new Dog[2];
myDogs[0] = new Dog("Bob");
myDogs[1] = this;
int x = 0;
while (x < myDogs.length) {
System.out.println(myDogs[x].name); // Would this print "Bob" and then "Ben"?
}
}
public Dog(String newnname) {
this.name = newname;
}
}
No comments:
Post a Comment