Rk R Bairi
Rk R Bairi

Reputation: 1359

Ways of accessing a static nested class in Java

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(){}
    }
}

Upvotes: 0

Views: 63

Answers (1)

l'arbre
l'arbre

Reputation: 719

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()
    }
}

Upvotes: 1

Related Questions