0

I have learnt that static nested class should be accessed like a field of outer class(line 2). But even instantiating the inner class directly worked (line 1). Can you please help me understand?

public class OuterClass { public OuterClass() { Report rp = new Report(); // line 1 OuterClass.Report rp1 = new OuterClass.Report(); // line 2 } protected static class Report() { public Report(){} } } 
3
  • 1
    Unrelated, but please consider normalizing your indentation. In any case, you're accessing it from inside the containing class, so there's no need to prefix it with OuterClass. It's when you're accessing an exposed inner class from outside the containing class that you need to qualify it. Commented Nov 29, 2016 at 16:34
  • also unrelated: the "Report()" should be "Report" Commented Nov 29, 2016 at 20:50
  • @Addi I don't understand. new Report() would call the default constructor of report class to create an instance right ? Commented Nov 30, 2016 at 21:41

1 Answer 1

1

accessed like a field of outer class

And that's what you are doing. Imagine this:

class OuterClass { SomeType somefield; static SomeType staticField; public OuterClass() { //works just fine. somefield = new SomeType(); //also works. I recommend using this this.somefield = new SomeType(); //the same goes for static members //the "OuterClass." in this case serves the same purpose as "this." only in a static context staticField = new SomeType(); OuterClass.staticField = new SomeType() } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.