简体   繁体   中英

Gaining access to instance variables from outside classes

I am fairly new to programming and I have a question about class access. Say that I create a class called TheClass with a bunch of public variables and public methods. I then create several other top-level classes that need access to the methods/variables of an instance of TheClass. So, when I create an instance of TheClass and I want to access the variables of that instance by other top-level classes, then it is my understanding that I can:

Pass the new instance of TheClass into the constructor of each of the other classes when they are created so they can access those variables inside of the instance of TheClass like this:

TheClass theClass = new TheClass(); 

OtherClass otherClass = new OtherClass(theClass);

Alternatively, I could nest all of the other classes inside of TheClass thereby giving them access to the variables of theClass instance... I think?

Finally, I could make variables/methods of TheClass static thereby giving other classes outside of TheClass access to them, however this is no good because I need access to the variables of the instance of TheClass that is running.

The reason I'm asking is because I recently created my first big program and I was passing an instance of a class object into a large number of other classes and It became quite a chore just following it around. I felt like I was doing something wrong. Have I overlooked something huge with regards to accessing instance variables of a class from other top-level classes?

I am a long ways away from understanding even the basics of Java programming but this is a question that keeps surfacing for me so I thought I would ask it here.

This is a common problem, and one of the reasons that things like the singleton pattern , dependency injection and application context (which is just a variant of singleton) are so popular.

They all allow you to minimize the passing around of objects all the time.

The first step is architecture. If you have your inheritance and composition right it reduces this - although it still exists.

The next option always used to be Singletons. (Application Context is just using one Singleton to then point to other resources from that Singleton). More recently Dependency Injection is by far the preferred route as it also makes things like unit testing a lot easier.

http://en.wikipedia.org/wiki/Dependency_injection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM