aspose file tools*
The moose likes Beginning Java and the fly likes class inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "class inheritance" Watch "class inheritance" New topic
Author

class inheritance

Grant Hackshaw
Greenhorn

Joined: Sep 28, 2005
Posts: 2
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Grant Hackshaw
Greenhorn

Joined: Sep 28, 2005
Posts: 2
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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
 
subject: class inheritance