This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
passing by reference in Java doubts
(5 answers)
Closed 8 years ago.
If I have a class like the one below:
public class Foo()
{
private RandomObject randomObject = new RandomObject();
public RandomObject GetRandromObject()
{
return randomObject;
}
}
And in another class I do this:
public class Goo()
{
private Foo fooObject = new Foo();
public Goo()
{
RandomObject ro = fooObject.GetRandomObject();
ro.ChangeNumberVariable(23);
}
}
Will the fooObject have the randomObject NumberVariable changed to 23?
If not would I just have to have a method in Foo called SetRandomObject and just pass in ro? Would this be a good substitute for passing by reference in Java?
What if I just did this:
public class Goo()
{
private Foo fooObject = new Foo();
public Goo()
{
fooObject.GetRandomObject().ChangeNumberVarialbe(23);
}
}
Is it still not changing the NumberVariable?
In both cases fooObject.randomObject would have NumberVariable changed to 23. They are pretty much equivalent just the former uses an extra reference.
This does not make Java pass-by-reference. Java is pass by value. Any time you pass something to a method as a parameter it is copied, even if what you pass is a reference to an object.
Though you can use that copied reference to access and mutate the object on the end of it, as you are doing here, any re-assignment of that reference cannot escape the method.
In your first example doing:
ro = new RandomObject();
would not change anything about fooObject.randomObject.
Related
This question already has answers here:
Different object and reference
(2 answers)
What does it mean to "program to an interface"?
(33 answers)
Java memory usage in inheritance
(2 answers)
Closed 4 years ago.
public class Test
{
public static void main(String args[])
{
A a = new B(); // object of type B
}
}
Here the object is of type Class B but is referred by a variable of type Class A
Doing A a = new A() and A a = new B() both only allow me to access members and methods of Class A then why should I instantiate variable a with constructor of Class B ?
How is this exactly represented in Memory and what exactly happens ?
Declaring a variable as an ancestor type allows you to switch the implementation on the fly. For example...
public static void main(String[] args) {
List<String> stringList;
stringList = new ArrayList<>();
// Stuff Happens and now I need a LinkedList...
stringList = new LinkedList<>();
}
If I declared stringList as an ArrayList from the start, I wouldnt be able to switch it to use a LinkedList instead.
As for how it looks in memory. My limited understanding is that the Compiler will care about the Declared Class for TypeSafety but Runtime and Memory will only care about the Instantiated Class.
This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 8 years ago.
I'm currently reading about the this keyword and don't understand why is it useful to do things like:
this.object = object;
(object is a random variable. I just don't understand why we do like, this.xxx = xxx)
Help me please!
It's necessary to specify that you want to assign the value to the field, rather than the parameter or local variable:
public void setFoo(Foo foo) {
this.foo = foo;
^ ^
| \--- Take the value of the parameter
\---- Assign to the field
}
If you just wrote:
foo = foo;
in the above, then it wouldn't do anything - it would be assigning the value of the parameter back to the parameter.
Another option, however, is to use a different parameter name instead:
public void setFoo(Foo newFoo) {
foo = newFoo;
}
Now the field and the parameter have different names, so you don't need to find another way to differentiate between them.
imagine having a setter like
private Object obj;
public void setObject (Object obj)
{
this.obj = obj;
}
this this scope the object to the class field otherwise with
obj = obj;
you would be setting the same object to be the same object.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
I'm working on translating some code from VisualBasic to Java and I've encountered a snag when using the ByRef keyword in VB. That doesn't exist in Java!
How should I simulate a ByRef call in Java?
Edit: Just to clarify for those who don't know VB, ByRef identifies a variable in the parenthesis after calling a function and makes it so that when that variable is changes inside of the function, it will also change higher up where it is called as opposed to ByVal where only the value of the variable is remembered. Changing a ByVal variable in the method will not affect the variable where it is called.
You can't. Everything in Java is passed by value, including object references. However you could create a "holder" object, and modify its value inside a method.
public class Holder<T> {
T value;
public Holder(T value) {
this.value = value;
}
// getter/setter
}
public void method(Holder<Foo> foo) {
foo.setValue(something);
}
Java does not have an equivialent.
You either need to return the object from your method, and assign it back, e.g.
myInteger = doSomething(myInteger);
Or you need to make a wrapper object, these are often name a Holder.
If you have a variable named myInteger that you want some method to change, you
pass it to that method as a member of the "Holder" class.
e.g. (This can naturally be made into a generic)
class IntegerHolder {
public Integer myInteger;
}
IntegerHolder myHolder;
myHolder.myInteger = myInteger;
doSomething(myHolder);
//use the possibly altered myHolder.myInteger now.
Inside doSomething, you can now change myHolder.myInteger , and the method calling
doSomething() can see that change, e.g.
void doSomething(IntegerHolder holder)
{
holder.myInteger = holder.myInteger * 100;
}
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
Code:
class AB{
int i=5;
}
class BC{
public void test(AB a){
a.i=10;
}
}
public class ATest{
public static void main(String aa[]){
AB a = new AB();
//Base class variable value
System.out.println(a.i);
BC b = new BC();
//Modifying the object "a"
b.test(a);
//Printing the base class object
System.out.println(a.i);
}
}
// Output : 5
// 10
If it is pass-by-value, the output should have been 5 and 5
Java uses pass-by-value but if the parameter is an object Java passes by value the reference to the object, so the called method can change the content of the object, not the object as a whole.
This does not mean that objects are passed by reference (the comment by Joachim Isaksson is wrong).
ADDED to answer to the comment by Arijeet Saha:
When I say "the called method can change the content of the object, not the object as a whole", I mean that if you change the object as a whole the caller doesn't see the change.
Consider the following example:
public void test(Person p) {
p.setName("Pino");
p = new Person();
p.setName("John");
}
The first line of test() changes the content of the object received by the method, the second line changes the object as a whole (it assigns a new object to the formal parameter), the third line changes the content of the new object. In this case the caller sees a Person object with name "Pino", not "John", because the change made by the second line of test() is not visible to the caller; it is not visible because objects are not passed by reference.
Let me first clear what does pass-by-value mean?
It means what ever you are passing to a method, it will recieve its copy not the actual adress.
So in your case you too are passing the value the variable a, and its value (which is referance to an object or adress to an object) is copied to the method(AB a).
Java's parameter passing is quite tricky - When an object is passed to a function, you can manipulate the object's fields but you cannot manipulate object itself. The object reference is passed by value. So, you can say:
class someClass{
int i = 5;
}
class Foo
{
static void func(someClass c)
{
c.i = 3;
}
}
class MainClass{
public static void main(){
someClass c = new someClass();
System.out.println(c.i);
Foo.func(c);
System.out.println(c.i);
}
}
Expect your output to be:
5
3
Changes to the fields of c persist.
but if manipulate the object itself, this manipulation will only persist in Foo.func() and not outside that function:
class someClass{
int i = 5;
}
class Foo
{
static void func(someClass c)
{
c.i = new someClass();
c.i = 3;
System.out.println(c.i);
}
}
class MainClass{
public static void main(){
someClass c = new someClass();
System.out.println(c.i);
Foo.func(c);
System.out.println(c.i);
}
}
Expect your output to be:
5
3
5
What has happened? c.i has the value 5 in MainClass.main() in Foo.func(), c itself is modified to point to another instance of someClass, containing the value 3. However, this change is not reflected to the actual object that has been passed. The c in Foo.func() and MainClass.main() are different objects now. That's why changes to the c of Foo.func() do not affect the c in MainClass.main().
Java always passes parameters as by value.
It's important to understand what is the value (what a variable holds).
For primitives it's the value itself.
For objects it's a reference.
When you pass an object as a parameter - the reference to the object is copied but it still points to the original object.
This question already has answers here:
What does "this" point to?
(5 answers)
Closed 4 years ago.
public class CommandForm extends Form implements CommandListener {
Display d;
public CommandForm(String msg) {
super(msg);
this.addCommand(exit);
}
private void showMessage(String title, String text) {
Alert a = new Alert(title, text, null, AlertType.INFO);
d.setCurrent(a, this);
}
public void prepare_view(Display d){
this.setCommandListener(this);
this.d = d;
}
public void show_view(){
d.setCurrent(this);
}
}
I do not know exactly what the 'this' keyword means in this example. My lecturer says it is the current object, when I inquire further, he said it is the CommandForm. Is that correct? When you pass in 'this' into a parenthesis, e.g setCommandListener(this) are you actually passing the CommandForm? The only way I know how to use 'this' is like this way, this.d = d. So this is kinda new to me.
He's right. If you call setCommandListener(this) you are passing a reference to the current object into the method. When you do this.d = d you are setting the variable d which is part of the class (i.e this) to the incoming value (in parenthesis).
Your lecturer is indeed correct. It's the current object, and this is simply a means to refer to the object currently in scope.
You use the keyword to pass the reference to other objects e.g. object.doSomethingWith(this), and/or resolve ambiguity between members and variables (e.g. this.x = x - there are two different xs here).
Check out the Java Language Specification section on 'this'.
Yes, the this keyword is a reference to that particular instance of the CommandForm class.