Delirium tremens
Delirium tremens

Reputation: 4739

nested methods

add and GetContentPane are methods

Does this code access a method in a method? What does this code do?

frame.getContentPane().add(BorderLayout.SOUTH, b);

Upvotes: 0

Views: 4299

Answers (4)

coobird
coobird

Reputation: 160964

In the code that is shown, it is not a "nested method", but a method that is being called on object that was returned from another method. (Just for your information, in the Java programming language, there is no concept of a nested method.)

The following line:

f.getContentPane().add(component);

is equivalent to:

Container c = f.getContentPane();
c.add(component);

Rather than separating the two statements into two lines, the first example performs it in one line.

Conceptually, this is what is going on:

  1. The f.getContentPane method returns a Container.
  2. The add method is called on the Container that was returned.

It may help to have some visuals:

f.getContentPane().add(component);
|________________|
        L  returns a Container object.

[Container object].add(component);
|________________________________|
        L  adds "component" to the Container.

This is not too unlike how substitution works in mathematics -- the result of an expression is used to continue evaluating an expression:

(8 * 2) + 4
|_____|
   L  8 * 2 = 16. Let's substitute that.

16 + 4
|____|
   L  16 + 4 = 20. Let's substitute that.

20  -- Result.

Upvotes: 4

Macarse
Macarse

Reputation: 93143

public class A {
 public A f1() {
   //Do something.
   return this;
 }
 public A f2() {
   //Do something.
   return this;
 }

Then:

A var = new A();
var.f1().f2().f1();

Upvotes: 1

S.P
S.P

Reputation: 8756

getContentPane() returns a Container, and add is one of the methods of the Container class.

So by doing frame.getContentPane() you're getting the Container object returned by it, and then calling the add method for that object.

Upvotes: 1

Toon Krijthe
Toon Krijthe

Reputation: 53366

A method can return an object. And you can call a method on that object.

There are languages that support local functions. But those are not visible from the outside.

Upvotes: 3

Related Questions