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);
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);
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.
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.
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();
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:
f.getContentPane
method returns a Container
.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.