Suppose we have a class World and we've declared an instance dreamWorld of that class. How Case 1 is different from Case 2 other than it's one line shorter? What difference does instantiating in the second case actually make? I mean, afterall dreamWorld will be just the same in both cases, right?
Case 1:
void changeWorld(World outerWorld) {
World dreamWorld;
dreamWorld = outerWorld;
}
Case 2:
void changeWorld(World outerWorld) {
World dreamWorld;
dreamWorld = new World();
dreamWorld = outerWorld;
}
where outerWorld is an object of World class created elsewhere and, say, provided as a method argument (I'm not sure if it matters how it is being provided).
PS
Thank you for all your prompt and helpful replies, guys, and sorry for my delayed gratitude (it took me time to read some literature that I felt would be necessary to fully understand your replies).
Case 2 is pointless. You instantiate a new World object and then lose the reference to it a line later when you assign dreamWorld = outerWorld, leaving it for the garbage collector to collect.
EDIT:
As #Rob pointed out, a caveat to the aforementioned statement is in the case that World's constructor performs some external interaction, instantiating it will still take an affect. Assigning it to dreamWorld, however, is pointless, as this reference will be lost.
In Case 1 you:
Declare a variable
Set the variable to a value
In Case 2 you:
Declare a variable
Create a new object
Set the variable to a value
Set the variable to a value
Destroy the recently created object
Both methods produce the same end result, but the second one also creates and destroys an object that was never used (which is, of course, entirely superfluous).
In Case 2, one extra object will be created in dreamWorld = new World(); line which will be garbage collected later because you are overwriting it
The only difference it makes is that you've allocated some memory for another World object, which will then be mopped up by the garbage collector since you immediately nuke its reference.
All of the other answers are correct 1 and 2 the result will be logically the same, but Case 2 creates an instance of the object that gets lost and will be garbage collected.. (wasted logic)
Something that others are not taking into account is that your compiler will most likely identify this and remove the logic and the end byte code will be identical plus or minus a compile warning..
This said the fact that you are asking the question would suggest that you are not fully aware of what is happening when you use a = operator on references.
dreamworld and outerworld will be pointing to the same object instance.. you copied the references you did NOT make a copy of the object. so if you change outerworld the dreamworld will change with it.. You must use method or construct your own method that will make a clone/copy of the outerworld instance an assign it to the dreamworld instance.
REVISION: Depending on what the constructor for World class does the outcome could be DRASTICALLY different. for example it could update a static member of the class, create a file or any number of things. :) But if the class is a simple Bean, and the constructor has no side effects then all the answers here hold :).
Obviously as stated in other answers your code is not setup properly. But 1 reason to instantiate would be if you were running this game on a server/multiplayer if person 1 got to level dreamWorld and person 2 started the game it would overwrite the World variable and person 1 would be magically on outerWorld.
Think of instantiation as creating an instance or object from a template.
You instantiate a class to create an object, a concrete instance of the class.
How to instantiate an object in java?
Related
There is a scenario
Say I have a class People & a utility class PeopleUtil with a method computeTotalNumberOfPeople
In a separate class say EvaluatePeople where I have code
People people = new People();
people.setValue(10);
people.setX(45);
PeopleUtil.computeTotalNumberOfPeople(people);
this.persistPeople(people);
In the computeTotalNumberOfPeople method
public void computeTotalNumberOfPeople(People people){
//logic for computing total no of people & then
int totalPeople = certainIntValue;
// I can return the totalPeople value from this method but I am not doing it just for the sake of this scenario
people.setTotalNumberOfPeople(totalPeople);
}
When I look at the People object in the db row I see the totalNumberOfPeople value persisted. Which is actually fine.
My question is, I am a little confused about it, shouldn't computeTotalNumberOfPeople method return the people object, which has an extra set value, to the method caller code & then that object should be passed to the peristPeople method as an argument?
I hope you understand what I mean, it doesn't seem right someway
Objects are mutable – they can be changed.
So when you call people.setTotalNumberOfPeople(totalPeople), you are setting the totalNumberOfPeople variable (or whatever it's called inside the People class) to totalPeople for the people object.
When you exit the computeTotalNumberOfPeople method, the object is still the same one that was modified – the changes from the method persist.
One way to think about it is passing a reference to people. When you call computeTotalNumberOfPeople(people), you are passing a reference to people. When people is modified, you modifying the same location in memory, and so the changes persist.
I have a coding dilemma, and I don't know if there's a pattern or practice that deals with it. Whenever I have to pass some values to a method, most times I try to pass only the needed objects, instead of passing the objects which are being composed by them.
I was discussing with a friend about how Java manages heap and memory stuff and we didn't get anywhere.
Let me give two examples:
//Example 1:
private void method doSomething(String s, Car car, boolean isReal){...}
...
String s = myBigObject.getLabels.getMainName();
Car car = myBigObject.getCar();
boolean isReal = myBigObject.isRealCar();
doSomething(s, car, isReal);
//Example 2 - having in mind that BigObject is a really big object and I'll only use those 3 atributes:
private void method doSomething(BigObject bigObject){...}
...
doSomething(myBigObject);
In the 2nd example, it seems to me memory will be kind of wasted, passing a big object without really needing it.
Since Java passes only references to objects (and copies them, making it technically pass-by-value), there is no memory overhead for passing "big objects". Your Example 1 actually uses a little more memory.
However, there may still be good reason to do it that way: it removes a dependency and allows you to call doSomething on data that is not part of a BigObject. This may or may not be an advantage. If it gets called a lot with BigObject parameters, you'd have a lot of duplicate code extracting those values, which would not be good.
Note also that you don't have to assign return values to a local variable to pass them. You can also do it like this:
doSomething(myBigObject.getLabels().getMainName(),
myBigObject.getCar(),
myBigObject.isRealCar());
You're already only passing a reference to BigObject, not a full copy of BigObject. Java passes references by value.
Arguably, you're spending more memory the first way, not less, since you're now passing two references and a boolean instead of a single reference.
Java uses pass by value, when ever we pass an object to a method keep in mind that we are not going to pass all the values store in side the object we just pass the bits( some thing like this ab06789c) which is the value of the address on which the object is stored in memory(Heap Memory). So you are wasting more memory in first case rather than the 2nd one. Refer to JAVA pass-by-reference or pass-by-memory
All references are the same size, so how could it use more memory? It doesn't.
For example, is this code valid?.
class abc{
int x,y;
abc(int x,int y){
this.x=x;
this.y=y;
while(true)
update();
}
public void update(){
x--;
y--;
if(y==0)
this=null;
}
}
If the above is not valid, then please explain why. I am in need of a class that after certain iterations ceases to exist. Please suggest alternatives to the above approach.
No, this code is not valid.
Furthermore, I don't see what meaningful semantics it could have had if it were valid.
Please suggest alternatives to the above approach.
The object exists for as long as there are references to it. To make the object eligible for garbage collection you simply need to ensure that there are no references pointing to it (in your case, this should happen as soon as y reaches zero).
No. The reason is that you do not make object null. When you say obj = null; You just put null to variable that previously hold reference to object. There are probably a lot of other references to the same object.
I think that what you want to do is to kind of invalidate object and make it garbage collected but take this decision inside the class. If this is the problem I'd recommend you to take a look on weak references.
Other possible solution is to implement kind of "smart reference" in java. You can create your class SmartReference that will hold the real reference to the object. The object should hold callback to this smart reference and call its method invalidate() that is something like your syntactically wrong expression this = null. You have to care not to refer to such objects directly but only via smart reference.
The only question is "why do you want to do this?". Really, this will cause the code to be more complicated and unstable. Imagine: the object decides to invalidate itself, so the reference that "smart reference" is holding becomes null. Now all holders of this smart reference will get NPE when trying to use the object! This is exactly the reason the such mechanism does not exist in java and that application programmer cannot mange the memory directly.
Bottom line: remove all object references and let GC to do its hard job. Trust it. It knows to clean the garbage.
I think this is a good question.
I've had loads of cases where I'd like Objects to validate themselves after/during construction and if it finds reason to, to just return an empty value or go back up the stack and skip over creating that object.
Mostly in the case of where you are creating a list of objects from a list of other values. If a value is garbage and you want your object to recognise this.
Rather then have to code a function outside the Class itself to validate the creation, it would be much neater to allow the object to do it.
It's a shame java doesn't allow for things like this on the assumption the programmer is probably going to mess it up. If you code well it would be a nice feature.
I think you need to rethink why you want to do this, because what you're suggesting doesn't even exist as a concept in Java.
The this variable always refers to the object itself. You can't "nullify" an object, only a reference (since after all, what you're doing is assigning a reference to point to null instead of its previous object). It wouldn't make sense to do that with this, as it's always a pointer to the current object in scope.
Are you trying to force an object to be destroyed/garbage collected? If so, you can't do that while other parts of your code still have references to it (and if they don't have references, it will be garbage collected anyway).
What did you hope/think this would do, anyway?
your code must be get compile time error..
Coz..
The left-hand side of an assignment must be a variable
this is not a variable its a keyword..
this=null;
I am trying to understand a sample code in Webots (robot simulation program).
I have faced this code :
Servo rightShoulderPitch = getServo("RShoulderPitch");
rightShoulderPitch.setPosition(1.5);
I do not understand what is meat by the first line. It look like that "rightShoulderPitch" is an object of Servo class but it is not created as usual and how 'getServo' (i think it is a method) comes here .
This class's header is, if it helps:
public class FieldPlayer extends Robot {
Also it has description by the company in the reference manual, but I could not understand what they mean. It can be found here search for getservo.
--- RShoulderPitch: is the name of the shoulder of the robot
I will appriceite help very much.
Thanks
This line:
Servo rightShoulderPitch = getServo("RShoulderPitch");
... calls the getServo method, passing in the string value "RShoulderPitch". The return value is used as the initial value of the rightShoulderPitch variable, which is of type Servo. (Note that rightShoulderPitch isn't an object - it's a variable. It has a value, which would either be null or a reference to an object.)
We can't tell what the return type of getServo is, but it's got to be something which is implicitly convertible to Servo - so either Servo itself, or some subclass.
getServo could:
Create a new object, and return a reference to it
Return a reference to an existing object (e.g. from a cache)
Return null
Throw an exception
If none of that helps, please clarify exactly what you don't understand. It sounds like you may be new to Java - in which case, learning "just Java" without the Webots API would probably be a good approach; only learn Webots when you're confident in the language itself.
To complement Jon's excellent answer, I'll try to explain you in much more general terms.
When you want a sandwich, you have two solutions:
prepare the sandwich yourself. This would be the equivalent of the code Sandwich s = new Sandwich()
go to a snack bar and ask them a sandwich. This would be the equivalent of the code Sandwich s = snackBar.getSandwich("Ham & Cheese").
In the latter case, it's the snackBar object's getSandwich() method which will use the name of the sandwich you want ("Ham & Cheese") to prepare a sandwich and return it for you. This method will thus probably, internally, call new Sandwich(). But it could also delegate to another object and call, for example: cook.prepareSandwich("Ham & Cheese"). And in this case, it's the cook object which will call new Sandwich(). Or the snackBar object could also just get a sandwich that has been prepared in advance and stored in some cache: fridge.getSandwich("Ham & Cheese").
I have a basic doubt regarding object creation in java.Suppose i have two classes as follows
Class B{
public int value=100;
}
Class A{
public B getB(){
return new B();
}
public void accessValue(){
//accessing the value without storing object B
System.out.println("value is :"+getB().value);
//accessing the value by storing object B in variable b
B b=getB();
System.out.println("value is :"+b.value);
}
}
My question is,does storing the object and accessing the value make any difference in terms of memory or both are same?
They are both equivalent, since you are instantiating B both times. The first way is just a shorter version of the second.
Following piece of code is using an anonymous object. which can't be reused later in code.
//accessing the value without storing object B
System.out.println("value is :"+getB().value);
Below code uses the object by assigning it to a reference.
//accessing the value by storing object B in variable b
B b=getB();
System.out.println("value is :"+b.value);
Memory and performance wise it's NOT much difference except that in later version stack frame has an extra pointer.
It is the same. This way: B b=getB(); just keeps your code more readable. Keep in mind, that object must be stored somewhere in memory anyway.
If you never reuse the B-object after this part, the first option with an anonymous object is probably neater:
the second option would need an additional store/load command (as Hot Licks mentioned) if it isn't optimized by the compiler
possibly first storing the object in a variable creates slight overhead for the garbage collector as opposed to an anonymous object, but that's more of a "look into that" than a definitive statement of me
If you do want to access a B a second time, storing one in its own variable is faster.
EDIT: ah, both points already mentioned above while I was typing.
You will not be able to say the difference without looking at the generated machine code. It could be that the JIT puts the local variable "b" onto the stack. More likely however that the JIT will optimize b away. Depends on the JRE and JIT you are using. In any case, the difference is minor and only significant in extremely special cases.
Actually there is no difference in the second instance you are just giving the new object reference to b.
So code wise you cannot achieve the println if you use version 1, as you dont have any reference as you have in the second case unless you keep creating new object for every method call.
In that case the difference, if any, would not be worth mentioning. In the second case an extra bytecode or two would probably be generated, if the compiler didn't optimize them away, but any decent JIT would almost certainly optimize the two cases to the identical machine code.
And, in any event, the cost of an extra store/load would be inconsequential for 99.9% of applications (and swamped in this case by the new operation).
Details: If you look at the bytecodes, in the first case the getB method is called and returns a value on the top of the stack. Then a getfield references value and places that on the top of the stack. Then a StringBuilder append is done to begin building the println parameter list.
In the second case there is an extra astore and aload (pointer store/load) after the getB invocation, and the setup for the StringBuilder is stuck between the two, so that side-effects occur in the order specified in the source. If there were no side-effects to worry about the compiler might have chosen to do the very slightly more efficient dupe and astore sequence. In any case, a decent JIT would recognize that b is never used again and optimize away the store.