Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

class inheritance

 
Grant Hackshaw
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have written code similar to what is below.
Can anyone explain to me why the instance of class1 created in class2 can't be referenced in class3?


[ EJFH: Added [code ][ /code] tags to preserve formatting. ]
[ March 26, 2006: Message edited by: Ernest Friedman-Hill ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

Variables defined inside of a method are "local variables" -- their names are not visible outside of the method in which they're defined. The variable "class1" is local to the method "main" in Class2, and therefore is available nowhere else.
 
Grant Hackshaw
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Earnest 4 the warm welcome and the fast reply.

So I should declare variable class1 outside of the method, is that the trick if I need to use it in Class3?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, looking at your code and trying to guess what you want to accomplish: you want to call someFunction() and have it operate on a specific instance of Class1, created by Class2. The best way to do this, instead of using member variables like (yuk) global variables, is to give someFunction() an argument -- i.e., define someFunction like



Then you can create a Class1 in Class2.main() and pass it to Class3.someFunction(), like this:



Although this may look like a small change, it's really rather profound. What we've done is to decouple Class3 and Class2. Class3 doesn't need to know anything about Class2, and this makes it easier to write the classes and to maintain them when they need to change. The main reason is that it makes everything easier to understand: you can see what someFunction() does without knowing anything about any other class that might use it.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic