This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 24183
    
  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: 24183
    
  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.
 
Consider Paul's rocket mass heater.
 
subject: class inheritance
 
Similar Threads
How to get a parent node reference in JXPath??
Accessing component from main class.... Help!
Top level clases
Refering to another class's instance of a different class, inside a class
Protected members