Passing a class instance into another class - java

I've looked everywhere but I can't seem to find an answer to this.
If I have one class (say, a Resource class) and another class (say a Sprite class) and each time I create a sprite, I pass in a reference to my Resource class (because it's required for some function) - am I correct in assuming, that all this does is creates a reference to this instance of said class?
So - if my Sprite constructor is this:
public Sprite(Resource res){
res.doSomething........
}
And I create 100 sprites, then this isn't going to cause problems because it's just passing in a reference or 'pointer'? (as opposed to creating a new instance each time).
Simple enough question I know, but I want to make sure I understand what's happening here and I couldn't find the answer to this anywhere.

Yes, if you create a new Sprite and pass it an existing Resource, the new Sprite will just have a reference to your original object.
So 100 Sprites would have 100 references to your 1 Resource.

Yes you have to create eachtime a new instance of the class to call doSomething() of that particular instance.

Related

Where does static variables and methods are loaded in java?

I am little bit confused that where did static variables and methods are loaded. we say that static variables and methods are loaded in the static memory. bt public static void main() is loaded into stack .Since main() method is also static then how it is possible that main is loaded into stack.
and alse is static methods and variable are stored in different positions because we say that methods are loaded in different place in memory.
The stack is where things go when they are invoked/executed. It doesn't matter if it is static or not. Any running function goes onto the stack where it's local variables and all are held until the stack frame is popped.
For example, I can have main() call main() recursively over and over. Each one would be a new stack frame. The fact that it is a static function does not change that.
Static variables, on the other hand, are different. There will only be one instance of them and you know it explicitly. So, they can go into special storage and be treated differently (as are other global things like the class definitions and all that).
The actual implementation of this is not liable to be very useful, nor easily understandable. However, a model of it might help you understand the use of these things.
First of all, data and code are quite different animals in Java. Variables are going to have values that change at runtime; code never does that. So when you instantiate a class, you are never going to get another copy of the code.
Consider the class Class - instances of it exist, one per fully-qualified class in the program. I think of all code for one class, static or not, as being associated with its Class instance -- 'loaded' with it, if you prefer. Incidentally, and coincidentally, that's also where I think of its static variables being 'loaded'.
But the instance variables need multiple copies -- whenever you instantiate the class, you need another copy of them. So they are associated (or loaded) with the instance of the class when instantiated -- think of the pointer to the class as a pointer to a structure that contains all the instance variables of that class, plus a pointer to jump tables to its methods, etc.
I do not know what you mean by public static void main being "loaded onto the stack". Do you mean the code? Code never goes onto a stack per se. It wouldn't make any sense to have code from a (normal) class put on the stack, lost when the current method returns, and then have to load it again if the method were called.
I think there's part of your question I'm not getting to because I don't understand what you're asking.

Is it possible for a constructor to call itself?

Is it possible for a constructor to call a class which is related to it? For example (in the code below) I am trying to create a new clock with ClockTimer and call the AnalogClock construct which has a ClockTimer parameter type. It doesn't seem to work because it gives me an error, but creating a new AnalogClock with the ClockTimer parameter in the ClockFrame class appears to work. What do I need to parse in AnalogClock (in the ClockApp) in order for it to run?
From the outside, it looks like the "analogClock" object needs the "timer" object to exist first, and the "timer" object needs the "analogClock" object to exist first.
In reality, thought, "timer" doesn't do anything with the "analogClock" ("clockFrame" inside "ClockTimer"), so it actually doesn't need it.
I'd suggest the following:
Remove the "clockFrame" parameter and field inside "ClockTimer"
Create the "timer" object first
Create the "analogClock" object second, and pass "timer" to it

Can a class instance variable be excluded from a subclass in Java?

Possibly a dumb question, but pretend class Node has an instance variable called strength. And pretend class Episode, which extends Node, does not need strength (other subclasses do). Pretend also that there are a LOT of Episode nodes all storing an instance of strength. Is there any way in Java to say "this subclass does not have a strength variable"? I'm kind of seeing why this probably isn't allowed, but thought I'd check.
Update: Thanks all. As I suspected, the answer to this question is "no," but creating a subclass of Node with the variables/methods not needed by Episode, then connecting the other (sub)subclasses that need these variables/methods to that new subclass will do exactly what I want.
No, it's not possible. You can have e.g. Node and StrengthNode classes, one without strength and one with it, then Episode class will extend Node, others will extend StrengthNode.
Also, take into account the access control in Java, as if strength is a private variable in Node, it will not be accessible in Episode class directly (only using getter method), but it's instance will exist in memory anyway.
Well The only way i can think around this is if your problem with the size of the object your instance variable stores either you can initialize the parameter to null or you can serialize the object with specifiying your instance parameters to be transient and go with serialize it , deserialize it .
This was just a thought around that , cant think of anything closer.
if you specifically dont need exact inheritance you go around that with creating a custom factory and extract the member variable using reflection , that would work too.
Anyway thats my opinion.

Studying Objects and Classes

I have a test later today, and I think I may be stuck on this part of the study guide:
Classes and objects, references, methods; the class as a pattern for
creating objects, the concept of a class and object as deļ¬ning a unit
with data members and methods; what is an instance of a class; static
members of a class; what it means for a member of class to be public
My best effort to explain these concepts is, as follows:
A class is a programmer defined data type that is composed of data
members and methods.
An object is an entity consisting of values
(characteristics and traits) and methods (capabilities or behaviors).
A class is like a blueprint from which objects are created.
A reference variable points to an object created in another memory location. (not 100% sure what this means)
Much like a cookie cutter can be used to create individual cookies, a class can
be used to create individual objects, or instances of that class.
A static member of a class (or class variable or method) belongs
to the class and is not owned by any object of the class.
If a member of a class is public, that means that it can be accessed by other parts of the program.
I'm wondering if this is going to be satisfactory or if I'm missing anything critical. Obviously I'm shaky on the idea of reference and reference variables, and I think I'm still trying to conceptualize objects and classes in a way that's sufficiently explainable.
Thanks for your help, in advance.
A class is a template from which objects can be built; it acts as a blueprint for creating objects.
An object is an instance of a class.
Much like how an architect draws a blueprint of a house. The blueprint and constructed house are two different things. From that one blueprint, the same house can be built in a lot of places. Similarly, you can create multiple objects of a class.
The blueprint defines how a house is supposed to look like. There is going to be a kitchen, a couple of bedrooms, a basement (possibly for hiding illegal money), etc. Each person who buys a house will customize the house in a different way.
This is akin to values in an object - same variables in different objects may have different values.
Get it? Same bedroom in two different houses constructed from the same blueprint will have different color, bed, lighting, etc. Same thing, different value.
Here is how you understand static and instance variables. The kitchen belongs to everyone - it is static and is shared by everyone and only one kitchen exists (static). Your guitar belongs to you and you only, it is not shared with anyone but it may happen that you sister also has a guitar that belongs to her and her only.
What I am saying is - every object has its own copy of instance variables while there is only one copy of static variables that is shared by all the objects of that class.
Here is how to understand changing the values of static and instance variables
If you were to get custom graphics for your guitars, it will matter to you and you only because it is an instance variable. If there was some change made to the kitchen, say the fridge was moved, it affects everyone because kitchen is a static variable.
What I am saying is - changes to instance variables are only visible to the object that owns them while changes to static variables are visible to all the objects of that class.
Seems pretty spot-on to me. If I'm being pedantic, I'd recommend changing the last two sentences:
A static member of a class belongs to the class and is not owned by
any instance of the class.
If a member of a class is public, that means that it can be accessed
by other classes within the program.
To understand references, you also might want to read this: http://www.javaranch.com/campfire/StoryCups.jsp
And its follow-up: http://www.javaranch.com/campfire/StoryPassBy.jsp
You seem to have everything else nailed down pretty pat. For newbies, reference types and reference variables are continuous points of contention because they have a tendency to get confused with something else.
The easiest way to understand reference types is to compare it in terms of houses. Your house is the value, your street address is a pointer to your house (a reference), and your full address -- could -- be considered to be your reference variable when used on an envelope.
See what I did there?
For the most part, you seem to have the material down. I'm going to try and answer your implied question here,
A reference variable points to an object created in another memory location. (not 100% sure what this means)
A reference (in Java) is a bit like a po box number. You can go to the post office and find lots of po boxes, but the number makes the specific box easy to find. Also, it is unique within the post office. It ensures the mail is kept separate from the other boxes. The analogy is not perfect (note the key is largely immaterial to this discussion).
Yes you are spot on with classes and how objects are instances of them. A class is like a template that contains all the attributes/characteristics. Within a class, there can be objects, which are more of instances of the class. For an example, say there's a class called 'Animal'. That means whatever items are in the class all have one thing in common: they're animals. Now, an object of the class 'Animal' would be a specific animal (bird, elephant, giraffe, dog). These would be objects under the class 'Animal' because they're all animals, but they're objects because they are instances of animals (kinds of animals). Also, when a member/method of a class is public, it can be accessed by other parts of the program or project. Hope this helps.

Create another instance of a dynamically loaded class - Java

So I have created an instance of a class by searching through jar files with no problems, I have it set to create an instance using c.newInstance() (Is instance the right word to use here?)
Later on in the program I may want to create another instance of that class if a certain event occurs. How can I go about creating this without having to search through all of the Jar files until I find the right one and then creating it again? Is there a way to create it somehow if I still have a reference to the first one?
Please assume that I do not know the name of the classes that will be loaded until runtime and there will be multiple classes that will be loaded.
Thanks
Save a reference to the Class of your object
Class c = dynamicObject.getClass();
and
and you can create a new instance like this (assuming there is a parameterless constructor)
Object anotherDynamicObject = c.newInstance(); // you can cast accordingly
else, say there is a consturctor that takes int, you can do
Constructor constructor = c.getConstructor(int.class);
Object anotherDynamicObject = constructor.newInstance(1);
Assuming "x" is the object you created ...
x.getClass().newInstance();

Categories

Resources