Friday, November 11, 2011

Static member classes and instance variables.

Tip: Static member class doesn't have access to non static members of outer class.

Like always, let's test it with a small code snippet:

public class Dolls {
    public int dollCount = 25;
    public static class Barbie{
        void printVar () {
            System.out.println(dollCount);
        }
    }
    public static void main(String[] args) {
        Dolls.Barbie barbie = new Dolls.Barbie();
        barbie.printVar();
    }
}

We have defined a top level class Dolls with static member class Barbie and member variable dollCount. Within Barbie we have used dollCount

If you try to run this example you will get a compilation error where dollCount is referenced within Barbie. 

Compilation error validates today's tip. 

Available in Android Market

No comments:

Post a Comment