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(){}
    }
}
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
Rk R Bairi
  • 1,289
  • 7
  • 15
  • 39
  • 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. – Dave Newton Nov 29 '16 at 16:34
  • also unrelated: the "Report()" should be "Report" – l'arbre Nov 29 '16 at 20:50
  • @Addi I don't understand. new Report() would call the default constructor of report class to create an instance right ? – Rk R Bairi Nov 30 '16 at 21:41

1 Answers1

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()
    }
}
l'arbre
  • 719
  • 2
  • 10
  • 29