I was wondering if anyone could help me. I am stuck with something that seems simple. Say I initialize a Student object with the values of name, age and address in one class. How can I share THAT INSTANCE with another class, eg enable methods in the second class to make changes to the instance, thereby affecting the first class etc.
I was thinking of using JFrames where a new frame would popup and a button would affect values on the first frame.
Thank you
mutators can help you there. or, the singleton pattern, if you want to go "hard-knox".
it's a pattern that allows only one single instance of a class in a jvm to exist.
just look at this
in java if you pass reference of an object to a method and do any changes to that object property, it will change the actual object properties(call by reference)
also if you want to have only single object of a class that needs to be shared across other classes create a singleton pattern
Related
Developing a jogl application, this is (a part of) our core class structure
main jFrame
viewer (for rendering)
inputListener
viewpole (for camera/projection control)
graph (holds nodes/meshes)
icon handler (to expand/collapse a node with children)
So if I want to call methodX() in the icon handler(that is basically the texture representing the handler, it is the same for all the nodes), I have to call:
Main.instance.getViewer().getGraph().getIconHandler().methodX()
where instance is a static variable holding the instance of the main jFrame
Given they are all:
1) instantiated once
2) at the begin
3) are supposed to be there for the whole time
4) in theory, no problem of race conditions, we are using java.util.concurrent.locks.ReentrantReadWriteLock at lower level when we add/read/modify/delete nodes
is it dangerous/bad design assigning the instance of each class to a static variable inside each corresponding class?
so that if I want to access the same methodX() I would just call
IconHandler().instance.methodX()
Ps: I read some of the other questions regarding static variables() but I found them quite generic, mine regards the core parts.
As long as you know that you'll only ever need one instance of each class, this is okay. This is called a singleton and is a pretty well-known design pattern.
The problem is that you probably can't guarantee that you only need one instance of your classes. Singletons are good for things like data connections or file readers, where there is a built-in limit to the number of instances that should access the data.
You're misusing the static keyword as a lazy way to gain access to an instance of a class, and it's going to come back and bite you when you expand your program to include multiple instances of those classes. And if you think you'll only ever need one instance- you can't guarantee that will never change.
I want to find instances of a class and modify some of the properties of one of the instance. But i cannot find a way to break in a block of code that references that class, so that it may appear in the variables view. What i'm thinking is to pause the jvm and the search for instances of MyClass but i can't find a tool to do this. Someone got an idea ?
I would open the call-hierarchie of the constructor of this class. Mark the constructor, left click, call hierarchie. That will give you a list wherever the object gets instantiated.
I have been perusing the open source code of JMapViewer. If anyone else wishes to look at it, check the SVN.
In a nutshell, the main class is JMapViewer, which is an extension of a JPanel. There is another very important class called DefaultMapController which acts as a MouseListener for the main class.
The first weird thing I noticed is that the viewer has no references to the controller. The JMapViewer constructor instantiates an anonymous instance of the DefaultMapController, like this:
public JMapViewer() {
// other stuff
new DefaultMapController(this);
}
This seems to me to be a poor design choice, since the controller has tons of methods (options, toggles, etc - example shown below), which now can not be accessed at all, so what good are they?
public void setMovementMouseButton(int movementMouseButton) {
// changes which mouse button is used to move the map
}
The controller does have a reference to the viewer as shown in the first snippet above, which is how it is able to exercise control.
However, then I thought of something even weirder! If this anonymous instance of the listener has no references, why is it allowed to even survive? Shouldn't the GC destroy it quickly? Or is GC smart enough to know that a listener class which references a live JComponent must also stay alive to work properly, even if it has no name for some strange reason?
So, two real questions:
why does GC not destroy object?
is this indeed a poor design choice, or is there some way I'm unaware of to access the controller from the class which instantiates the viewer?
I want to contribute to this open source library, and my first idea for a change is to change the JMapViewer class to have a field referencing its controller, and to change the constructor to assign the currently anonymous controller to this new field. But, I want to make sure I'm not ignorantly missing something. I have searched the entire codebase for the text DefaultMapController, and it only occurs in its own class definitions, and in the anonymous instantiations in the JMapViewer constructors.
EDIT:
It does indeed appear that there is a way to access the anonymous listeners, by using the java.awt.Component method getMouseListeners(). So technically in my application I could search this collection for instances of DefaultMapController, and use that to access the methods I need to use to change the controller options.
To play devil's advocate though, if I go with original idea and give the map a reference of its controller, now I have a sort of circular reference (map knows of controller and controller knows of map). Is this a bad idea?
The abstract parent, JMapController, holds a reference to the JMapViewer passed there by the DefaultMapController constructor:
public DefaultMapController(JMapViewer map) {
super(map);
}
Addendum: The map reference held by the controller is used to (selectively) add up to three controller references to the map's EventListenerList, discussed here. Any one of these would preclude GC. At least one salutary design benefit is that a concrete JMapController need only implement available interfaces.
As suggested in this MVC outline, it would be unusual to give the view a reference to the controller. In contrast, there's nothing wrong with letting the controller register as a listener to the view, as suggested here.
Note that only the no-argument JMapViewer constructor installs a DefaultMapController. You can use the alternate constructor, as noted in comments at line 57-59 in revision 29113 of Demo.java. A complete example is examined here.
1) Everything you know is that, if and when the VM deems it to be appropriate, it will collect some or all of the dead objects. The GC is not required to do anything.
2) The best thing is to ask to the maintainer of the library. Anyway, as a general rule, I would not bother to change anything unless there's a good reason to, e.g. if it sensibly improves readability, and would rather focus myself on real problems.
3) Not sure if that's the case, but, when you serialize a JComponent, you also serialize all of its fields. And you do not want to serialize a lot of unused stuff.
Im trying to change the method of just one instance from another class. Is this possible, and if so how can I do it?
Im trying to rewrite the entire method durring runtime. I only want the method to be changed for one instance of the class, and all the other instance's methods should stay the same. I hope that clears up some confusion
No this is not possible.
Method definitions are stored by class, not instance (and are immutable anyway). One thing you can do is to store a callable object per instance and call that.
I think you need to provide more details and perhaps some sample code to get a sufficient answer. That being said, if class Foo extends class Bar, class Foo can override a method of class Bar. Is that what you're trying to do?
I have a GUI class with a menu of buttons and textfields. Depending on what choices that is made in the menu and the input, methods in the GUI class are calling methods in the Logic class to send the input and create new objects of Customer class and Account class and so on.
To be able to communicate between the GUI- and the Logic class, I first create an object of the Logic class and I do that inside the GUI class, since it's here I have my main method. It this the best way to do it? Do I need some kind of reference variable between GUI- and Logic class or just use the reference when the object was created in the beginning of the GUI class? I guess to be able to communicate with a class, it must be an object first!? Thanks!
Logic logic = new Logic();
logic.addCustomer(name, number);
Ideally you shouldn't directly create the logic class.
You should break down the functionality into a number of small classes, each of which satisfy a responsibility.
A simplistic way would be for the GUI class to create listeners which listen to the user events. In response the to the use event they fire events that your logic registers itself for. Then when the event is received the logic class can perform the functionality.
You should read about observer pattern, event driven design...
You can read about event driven programming here http://en.wikipedia.org/wiki/Event-driven_programming .
I would instantiate the Logic class outside the GUI, but pass it as an argument to the GUI constructor. It's nearly equivalent to what you are already doing, but I think it makes it clearer that the GUI uses a Logic object. Also, it's possible that Logic does some other things before/after the GUI starts/closes; it might not be the case now, but it could be true in the future if you extend your program.
Many other answers tell you to look at MVC, but that might be overkill for your project. It can decrease complexity for a large project, but increase it for a small one.
EDIT:
Logic login = new Logic();
...
MyGUI gui = new MyGUI(logic);
...
I would suggest you do some researches on the MVC architecture. Your GUI (view) shouldn't interact directly with your model (logic). Implement a controller that will get the "signals" from your view and will be in charge to create your "logic objects" and work with them.
You can create on object of type Logic in your main and store a reference of the object in your Window object - so you can access your Logic object as long as the window exists.
You should look up the Singleton design pattern for such trivial scenarios.
By default, Java uses Reference variables. Hence, if you instantiate your object in GUI class, make sure you send the object via method calls to your processing class.
Alternatively, you can look into singleton classes, which will return only one instance of the class. Inside that class, instantiate all the objects that you will need globally, and re-use that instance throughout your program.
Generally you can. If your application is very simple.
But this approach is not scalable. As your application gets more complex it became much harder for development and support. Try to consider Model–view–controller pattern to define a best way for your design. (according to your nick name I'll take a risk to propose an alternative link)