Probably a very noob question
I am new to java and am reading a third party api written in java...
I came across this declaration
Foo foo = new FooBar().new Foo();
I am unable to understand
FooBar().new
Why is this declaration like this?
What advantages does one get in declaring something like above and what are the alternatives to such declaration.
Any advice/references would be greatly appreciated.
THanks
In java, String is a class . But we do not have to use new keyword to create an object of class String where as new is used for creating objects for other classes.
new is a Java keyword. It creates a Java object and allocates memory for it on the heap.
Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
FooBar
contains an inner class like this
class FooBar {
class Foo {
...
}
}
A new instance of the outer class is required to instantiate the inner class. Some classes don't make sense on their own so are implemented as nested classes. Here Foo
has a relationship with FooBar
and also has the benefit of having access to all of the latter's member variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With