Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Access an object via reference variable (or not)

 
Paolo Dina
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. Hope the qustion is not too silly, but I prefer to know if I have missed something along the way. Chapter on polymorphism (KB page 95):
Remember that the only way to access an object is through a reference variable...


If it is true what the book says and if it's correct that:


I'm wondering why the following code compiles and runs if Line 1 is not using a reference variable to access the object.



Thanks.
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a little tricky. The point is that the result of an instance creation expression is an anonymous reference of the same type as the class being created (read the JLS if you don't believe me )

So:

String s = new B().bMethod(); // Result of new B() is a reference of type B

There is always a reference involved, whether explicitly coded, or implicit.

I hope that helps to clear your doubts.
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
new NoRefTest() ==> Only a new object created, that can be referenced by reference variable.

new NoRefTest().isValid(); ==> new object is created and then a method of it is called in the same line. The method returns a boolean value that you cannot put in a reference variable, but in a boolean variable.
 
Paolo Dina
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, the (in)famous implicit reference, then I guessed well...

Thank you very much!
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I delete my post ..dont see the option any more
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paolo Dina wrote:Ah, the (in)famous implicit reference, then I guessed well...

Thank you very much!

You are welcome, Paolo. I also wondered about this at some point. Then checked the JLS and all the doubts were gone.
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Himalay Majumdar wrote:How do I delete my post ..dont see the option any more

Unfortunately that option is gone (but will hopefully resurface at some point.) For now, you are left with the option of editing your post and deleting its content (replace it by something like: Deleted.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic