Search code examples
javanested-class

Accessing static member class


I learnt that, to access the static member class, the syntax is OuterClass.NestedStaticClass.

For the given below interface Input,

interface Input{

    static class KeyEvent{
        public static final int KEY_DOWN = 0;
        public static final int KEY_UP = 0;
        public int type;
        public int keyCode;
        public int keyChar;
    }

    static class TouchEvent{
        public static final int TOUCH_DOWN = 0;
        public static final int TOUCH_UP =0;
        public static final int TOUCH_DRAGGED = 2;
        public int type;
        public int x, y;
        public int pointer;
    }

    public boolean isKeyPressed(int keyCode);
    .....
    public List<KeyEvent> getKeyEvents();
    public List<TouchEvent> getTouchEvents(); 
}

below is the implementation Keyboard,

class Keyboard implements Input{

    ....

    @Override
    public List<TouchEvent> getTouchEvents() {
        TouchEvent obj1 = new TouchEvent();
        TouchEvent obj2 = new TouchEvent();
        List<TouchEvent> list = new ArrayList<TouchEvent>();
        list.add(obj1);
        list.add(obj2);
        return list;
    }

}

In this implementation Keyboard, I did not require to use Input.TouchEvent for below lines of code.

TouchEvent obj1 = new TouchEvent();
TouchEvent obj2 = new TouchEvent();
List<TouchEvent> list = new ArrayList<TouchEvent>();

But for the below implementation, I had to use Input.TouchEvent,

public class NestedClassInInterface {
    public static void main(String[] args) {
        Input.TouchEvent t = new Input.TouchEvent();
    }
}

How do I understand this?


Solution

  • From the Java Language Specification, concerning members of an interface type

    The body of an interface may declare members of the interface, that is, fields (§9.3), methods (§9.4), classes (§9.5), and interfaces (§9.5).

    and concerning the scope of a declaration

    The scope of a declaration of a member m declared in or inherited by a class type C (§8.1.6) is the entire body of C, including any nested type declarations.

    and concerning class members

    The members of a class type are all of the following:

    • [..]
    • Members inherited from any direct superinterfaces (§8.1.5)

    So, the type TouchEvent is declared in the type Input. It is a member of Input. Keyboard implements Input and therefore inherits its members. TouchEvent is therefore in scope in the body of Keyboard. You therefore don't need to qualify its use with its enclosing type.