1

How can I declare an object of an inner class inside a static class in java?

public class xyz { static class abc { ... // I want to declare an object of class a here. how can I do this? } class a { ... } } 
9
  • a varName;??? Commented Apr 24, 2017 at 19:22
  • 'a' is class name Commented Apr 24, 2017 at 19:24
  • Perhaps this is relevant. Commented Apr 24, 2017 at 19:39
  • 1
    It's a little confusing at first, but like all non-static members, they have to be accessed through an instance. So you need to make a xyz object in abc. Commented Apr 24, 2017 at 19:44
  • If you need an instance of a without an instance of xyz, you probably have a design flaw. Can you explain why you want this? Commented Apr 24, 2017 at 19:46

1 Answer 1

2

Instances of inner classes exist in the context of an instance of the enclosing class. So you must first create an instance of the enclosing class, and from there you can create an instance of the inner class. For example:

public class xyz { static class abc { a member = new xyz().new a(); } class a { } } 

More information: Oracle Java Tutorials - Nested Classes

Sign up to request clarification or add additional context in comments.

2 Comments

I've tried this way, but it shows an error. It's asks me to create method a() inside class'abc'.
'Non-static inner' is a tautology. See JLS #8.1.3.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.