• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple doubt

 
Mark Henryson
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In the above coding, I have one doubt:

p.getName() --> p is the reference variable holding the Person Object anf thru p we can invoke its method getName();

p.getCar().getName() --> what does this means? How many level of dot we can have. For example: ref-obj.method.??
 
Sunil Kumar Gupta
Ranch Hand
Posts: 824
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getCar() method is returning an object
of type car...
U can always use <b>.</b> to call the
methods of this object....
 
Mark Henryson
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so, x.y.z means
x - ref variable
y - object
z - method

Any other possibilities??
 
Rob Acraman
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
p is a reference to a Person object
p.getCar() is a reference to a Car object
p.getCar().getName() is a reference to a String object

In theory, so long as each method returns a reference to an object, you can string any number of "."s together.

In practice, it would be bad coding to put too many - certainly not more than what you've got here. For example, the following clearly does the same :



However, the advantage with splitting the code like this is it enables debugging and maintenance. You can log the value of myCar to ensure it's what you expected it to be, etc.
 
Jim Kiley
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have as many "dot" levels as you want. You can, for instance do

String carSubstring = p.getCar().getName().substring(5);

... or whatever else you want.

jk
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a fairly well known principle called the Law of Demeter which spells out the best practices for using this kind of multi-level access. In short: don't. If you find yourself using multiple dots in an expression, it's a clue that the code you're writing belongs in some other class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic