aspose file tools*
The moose likes Beginning Java and the fly likes Simple doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Simple doubt" Watch "Simple doubt" New topic
Author

Simple doubt

Mark Henryson
Ranch Hand

Joined: Jul 11, 2005
Posts: 200


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

Joined: Aug 26, 2005
Posts: 824
getCar() method is returning an object
of type car...
U can always use <b>.</b> to call the
methods of this object....


Lack of will power has caused more failure than lack of intelligence or ability.
My Blog | Red5 Resources | Technology Update | Daily Technology Tips
Mark Henryson
Ranch Hand

Joined: Jul 11, 2005
Posts: 200
so, x.y.z means
x - ref variable
y - object
z - method

Any other possibilities??
Rob Acraman
Ranch Hand

Joined: Dec 03, 2000
Posts: 89
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

Joined: Sep 09, 2005
Posts: 6
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

Joined: Jul 08, 2003
Posts: 24168
    
  30

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.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Simple doubt
 
Similar Threads
doubt on jsp:useBean tag
HFJ doubt
Can we modify a private variable outside a class?
useBean doubt
y null????