Method Calls

Hi

I'm trying to understand the following snippet of code without much success. I was wondering if someone here could please help me?

The code forms part of an expression (which I've ommitted):

Font.getDefaultFont().getHeight();

What I don't understand is how you can seemingly do multiple method calls from a single class. The Font class being used is javax.microedition.lcdui.Font.

Looking at the documentation, the way I understand it is that getDefaultFont() is a static member of class Font which returns a Font object, and that getHeight() is a public member of the Font class which returns an int.

What confuses me is the syntax. It seems that with this method call, the Font class is able to call 2x methods in a single line of code? What my question really is, what's going on with this line of code? Is it just simply a case of a class being able to call a static member and then a public member or is it a class can call a static member and that a static member can call any public member?

Thanks

[1060 byte] By [PerksGa] at [2007-11-27 10:22:16]
# 1

"Single line of code" is only a source-code construct. The bytecode has no real equivalent. We can invoke methods on either a class (static method) or an instance of a class (instance method). In your example, You invoke the static method Font.getDefault(), which returns an instance of the Font class. You then invoke the instance method getHeight() on that object. The fact that in source, this is done on one line of code, is irrelevant. In bytecode, the result of one operation (getDefault) is pushed on to the stack, and in the next operation, it's popped back off the stack and has another method invoked upon it

You can chain method calls to an arbitrary degree, if you so wish, but it's not always a good idea. Hides the source of an NPE, for one thing. The following is perfectly legal but inadvisable

MyClass.getInstance().getTracker().getFactory().getDefault().getFoo().getBar().pop().restart();

georgemca at 2007-7-28 17:15:02 > top of Java-index,Java Essentials,New To Java...