0

I am a beginner in java. I found this example and cant understand that how can we pass a "new" operator , to create an object inside the parameter of a constructor. Furthermore, its nested and there is another statement(as parameter) in the parenthesis.

For ex: inside the new 'Bufferedreader' we pass an new 'Inputstream' object , then again call a method inside the constructor: url.openStream(). I have seen this many times and i am confused as to why dont we create a new object reference to "InputStream i = null;' and then pass that to the constructor?

Also, in general, what does it mean to return a value from a method and assign it ta Class instance? Test t = x.getname();', where the value return should be a class type? I dont understand this, please help!

StringBuilder json = new StringBuilder();
try {
    URL url = new URL(sMyUrl);
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    try {
        String str;
        while ((str = in.readLine()) != null) {
            json.append(str).append("\n");
        }
    } finally {
        in.close();
    }
} catch (Exception e) {
    throw new RuntimeException("Failed to read JSON from stream", e);
}
  • 2
    "why dont we create a new object reference to "InputStream' and then pass that to the constructor?" <- Because this way is shorter and if you don't need a local variable to a parameter you pass it just makes sense to inline the creation. – OH GOD SPIDERS Jun 23 '17 at 13:15
  • 1
    This notation is used when we do not need an explicit reference to an object. You may want to take a look at my old question: https://stackoverflow.com/questions/30898219/life-cycle-of-a-new-object-without-reference – PM 77-1 Jun 23 '17 at 13:17
  • Thanks! but, then how can pass a statement to the "InputStream" constructor: (new InputStreamReader(url.openStream()));, . Are we allowed to pass any statement to a constructor? –  Jun 23 '17 at 13:18
  • 2
    "Are we allowed to pass any statement to a constructor" No, you must pass *expressions* (of the appropriate type) to the constructor. (An expression is something with a value, like `null`, `1`, `5 / 6`, `"hello"`, `new Something()`; a statement is something that (normally) ends with a `;`. Some expressions can be made into statements by adding a `;`, but statements can't be made into expressions). – Andy Turner Jun 23 '17 at 13:19
  • Then , that means that we can 'call a method' , return value from an expression inside any other method call and the value will pass to that inline method and then to the main method? Could you reference any example or document, which can explain this further. Thanks. –  Jun 23 '17 at 13:28

4 Answers4

3

A class instance creation expression (new Something(...)) is an expression like any other. It has type Something, and so can be used anywhere that you need a reference to a Something:

Something s = new Something();
someMethod(new Something());
new Something().methodOnSomething();
assert new Something() != null;
// etc.

There's not much difference between

Something s = new Something();
Other o = new Other(s);

and

Other o = new Other(new Something());

The main difference is that you can use the variable s afterwards in the first case.

If you don't need to refer to s afterwards, it's really a matter of preference/style/readability as to whether you create a separate variable or not.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
2

You create an object on the heap without the reference to it and after it been used its garbage collected.

// creates an object on the heap with 'foo' as a pointer to it.
Foo foo = new Foo(); 

// then the above reference can be passed, in this case to the constructor of the 'Bar'
Bar bar = new Bar(foo);

Nothing is stopping you from passing new object straight without a reference as well.

// in this case you are passign the object straight to the constructor of 'Bar'
Bar bar = new Bar(new Foo());

Above example is common when you are not setting anything on the object or the object is stateless.

Other than that you would create a reference to the object you are playing with and set something on it before passing it to.

// creates an object on the heap with 'foo' as a pointer to it.
Foo foo = new Foo(); 

// set the state of the object
foo.setBehaviour("clumsy");
foo.isFooDirty(true);

// then the above reference can be passed, in this case to the constructor of the 'Bar' with its state.
Bar bar = new Bar(foo);
LazerBanana
  • 6,865
  • 3
  • 28
  • 47
2

I have seen this many times and why dont we create a new object reference to "InputStream' and then pass that to the constructor?

Since there is no use of that further to make a variable. It's just one time use , so just inline will do. Just to save a line of code. No difference performance wise or so.

Also, in general, what does it mean to return a value from a method and assign it ta Class instance? Test t = x.getname();'

That mean that the method getname() from class x returning an instance of type Test. And the returned instance being assigned to t, to use it further.

for example:

public Test getname(){
  Test te = new Test();
  //do something or may not.
  return te;
}

so the returned te will gets assigned to the above t

LazerBanana
  • 6,865
  • 3
  • 28
  • 47
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You need to understand order of evaluation of statement/expression(operator precedence).

 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

From given example, right side (after = ) will be evaluated in order from right to left andnew will be evaluated before it is passed in to another constructor or method as argument, which means that it is not new Something() that is passed, it is that particular created new Object (after evaluation of new Something()) that is being passed. You might find helpful reading about Decorator or Wrapper pattern, where one object wraps another one, adding additional behavior.

fg78nc
  • 4,774
  • 3
  • 19
  • 32