-1

Consider the following java code.

public class A {

  public static void main (String [] args){

    Temp p = new Temp();
    p.name = "Name";
    new A().changeValue(p);
    System.out.print(p.name);
  }

  public void changeValue(Temp t){
    t.name ="changeValue";
  }
}

class Temp{
  String name;
}

Well I got confused about this line : new A().changeValue(p); this is the first time for me to see like this line! is this anonymous object or?? also what is the output please! please explain with steps .

thank you

Christian
  • 22,585
  • 9
  • 80
  • 106
Donni
  • 11
  • 5
  • 2
    Possible duplicate of [Java: how to call non static method from main method?](https://stackoverflow.com/questions/7379915/java-how-to-call-non-static-method-from-main-method) – that other guy Sep 10 '19 at 22:31
  • 1
    You could run the code to find the output yourself? Or are you confused about the output you get? – OneCricketeer Sep 10 '19 at 22:32

2 Answers2

1
new A().changeValue(p);

is this anonymous object or??

Yes, you are creating a new instance of A without assigning it to a variable name. Then you immediately call changeValue() on that object. Note that you can rewrite this as two lines that gives the same result:

A a = new A();
a.changeValue(p);

In fact, this is the preferred way.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

It's equivalent to

A temporary = new A();
temporary.changeValue(p);

Basically, since changeValue is not static, an instance of A is needed to invoke the method.

So the code is creating an instance and directly invoking a method on the object just created.

Jack
  • 131,802
  • 30
  • 241
  • 343