an object is created and assigned with out new or declaration - java

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").

Related

Passing an object as a parameter in Java

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.

What difference does instantiating make?

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?

Pass data through call stack without method modification

I've got some crazy task, that sounds like mission impossible. I need to pass some data through stack of methods, which I can't modify (can modify only the last one). Example:
SomeData someData; //not passed in method1
obj1.method1(...);
here is obj1 class code
obj1 {
someReturnClass method1(...) {
...
obj2.method2(...);
...
}
}
obj2 and method2 call some more methods, before they get to objN.methodM(). It can even be run in separate thread (so, ThreadLocal won't help). I need to access someData inside methodM, which is not passed through this stack as parameter.
I've got some concepts to get it through exception and double running methodM, but it looks ugly.
Do you have any ideas, how to pass someData to methodM()?
If you can't smuggle access any other way -- e.g. by adding a reference to SomeData into some other object that is passed through the call stack -- then you will eventually have to use a global variable. This is of course a poor design, but nothing else is possible given your constraints.
You mentioned in a comment that you may have several calls to your method "active" (is it recursive, or do you have multiple threads?) In that case, you will need to have a global collection instead, and have some way of inferring which element of the collection to select from the data that is passed through the call stack.
I understand that you need to access a local variable inside a method activation, of a method which you can't change, but which you know exists lower on the stack.
The obvious thing here is to work with the Java Debugging Architecture: http://docs.oracle.com/javase/7/docs/technotes/guides/jpda/index.html
This will allow you to examine the stacks of all threads.
Finally, I found solution:
Create JAAS Subject
Subject subject = new Subject();
Put data somewhere in subject's principals or credentials:
subject.getPublicCredentials().add(new String("Trololo"));
Get this subject and it's data anywhere you need (works even in another thread):
Subject subject = Subject.getSubject(AccessController.getContext());
System.out.println(subject.getPublicCredentials());
It won't work only in one case: thread started before subject was created.

Can a class be nullified from within the class itself?

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;

Regarding two lines of java code

I am trying to learn a java-based program, but I am pretty new to java. I am quite confusing on the following two lines of java code. I think my confusion comes from the concepts including “class” and “cast”, but just do not know how to analyze.
For this one
XValidatingObjectCorpus<Classified<CharSequence>> corpus
= new XValidatingObjectCorpus<Classified<CharSequence>>(numFolds);
What is <Classified<CharSequence>> used for in terms of Java programming? How to understand its relationships with XValidatingObjectCorpusand corpus
For the second one
LogisticRegressionClassifier<CharSequence> classifier
= LogisticRegressionClassifier.<CharSequence>train(para1, para2, para3)
How to understand the right side of LogisticRegressionClassifier.<CharSequence>train? What is the difference between LogisticRegressionClassifier.<CharSequence>train and LogisticRegressionClassifier<CharSequence> classifier
?
These are called generics. They tell Java to make an instance of the outer class - either XValidatingObjectCorpus or LogisticRegressionClassifier - using the type of the inner object.
Normally, these are used for lists and arrays, such as ArrayList or HashMap.
What is the relationship between XValidatingObjectCorpus and corpus?
corpus is just a name given to the new XValidatingObjectCorpus object that you make with that statement (hence the = new... part).
What does LogisticRegressionClassifier.<CharSequence>train mean?
I have no idea, really. I suggest looking at the API for that (I think this is the right class).
What is the difference between LogisticRegressionClassifier.<CharSequence>train and LogisticRegressionClassifier<CharSequence> classifier?
You can't really compare these two. The one on the left of the = is the object identifier, and the one on the right is the allocator (probably the wrong word, but it is what it does, kind of).
Together, the two define an instance of LogisticRegressionClassifier, saying to create that type of object, call it classifier, and then give it the value returned by the train() method. Again, look at the API to understand it more.
By the way, these look like wretched examples to be learning Java with. Start with something simple, or at least an easier part of the code. It looks like someone had way too much fun with long names (the API has even longer names). Seriously though, I only just got to fully understanding this, and Java was my main language for quite a while (It gets really confusing when you try and do simple things). Anyways, good luck!
public class Sample<T> { // T implies Generic implementation, T can be substituted with any object.
static <T> Sample<T> train(int par1, int par2, int par3){
return new Sample<T>(); // you are calling the Generic method to return Sample object which works with a particular type of generic object, may it be an Integer or a CharSequence. --> see the main method.
}
public static void main(String ... a)
{
int par1 = 0, par2 = 0, par3 = 1;
// Here you are returning Sample object which works with a sequence of characters.
Sample<CharSequence> sample = Sample.<CharSequence>train(par1, par2, par3);
// Here you are returning Sample object which works with Integer values.
Sample<CharSequence> sample1 = Sample.<Integer>train(par1, par2, par3);
}
}
<Classified<CharSequence>> is a generic parameter.
LogisticRegressionClassifier<CharSequence> is a generic type.
LogisticRegresstionClassifier.<CharSequence>train is a generic method.
Java Generics Tutorial

Categories