Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to understand new keyword in java

Tags:

java

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

like image 201
frazman Avatar asked Jun 03 '13 17:06

frazman


People also ask

Why new keyword is not used in string in Java?

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.

What does :: new mean in Java?

new is a Java keyword. It creates a Java object and allocates memory for it on the heap.

What is the purpose of new keyword while creating object?

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.

What is the this keyword in Java?

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).


1 Answers

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.

like image 102
Reimeus Avatar answered Oct 26 '22 05:10

Reimeus