简体   繁体   中英

Java: Creating new custom object in main function?

I created an object within a class:

private class Viscosity{
    float magnitude;
    private Viscosity(float Magnitude){
        magnitude = Magnitude;
    }
}

In my main function, I attempt to extract data from a text file and create a new Viscosity object, but it seems that I cannot access this private object.

For example, I want to add it to a List of Objects:

listofObjects.add(new Viscosity(50.0f));

But I receive the error:

No enclosing instance of type is accessible. Must qualify the allocation with an enclosing instance of type ClassName (egxnew A() where x is an instance of ClassName).

How can I accomplish this?

You want to declare that class static if it does not depend on an enclosing instance:

 private static class Viscosity

Or, instead of calling it from the static main method, make an instance of the outer class and move your code into an instance method.

But, really, why does this have to be an inner class? Why not a regular (package-private) class. You can even declare it in the same file if you really want (but that is also not really advisable).

You should:

  • Make Viscocity a non-inner class. Declare it in its own file, unless you've got a very compelling reason to make it an inner class (which you've not yet made to us).
  • Make its constructor public.

Does your inner class need access to any members of the enclosing class? If not, you could make it a static class.

private static class Viscosity {
...

You can think of non-static nested class as member of its outer class, so you can use it only via instance of outer class (enclosing). Normally you will firs need to create some outer class instance like `

Outer out = new Outer() 

and then use this object to make instance of its inner class like

Outer.Inner inner = out.new Inner(). 

But to be able to do it your inner class and its constructor will have to be accessible in place you are trying to invoke this code.

There is no problem in using just new Inner() inside non-static methods of Outer class because it will be converted to this.new Inner() and this reference contains current instance of Outer class.
But there is problem with static methods because there is no this inside them, or this can contain wrong instance like if you are invoking new Inner() in class that doesn't extend Outer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM