0

I was looking through Beginning Android Games 2nd Edition and came across some code that I don't understand. In Listing 3-1 there is an interface defined as fallows

  public interface Input
     {
     public static class KeyEvent 
     {
      public static final int KEY_DOWN = 0;
      public static final int KEY_UP = 1;
      public int type;
      public int keyCode;
      public char keyChar;
     }
     public static class TouchEvent
     {
      public static final int TOUCH_DOWN = 0;
      public static final int TOUCH_UP = 1;
      public static final int TOUCH_DRAGGED = 2;
      public int type;
      public int x, y;
      public int pointer;
     }
     public boolean isKeyPressed(int keyCode);
     public boolean isTouchDown(int pointer);
     public int getTouchX(int pointer);
     public int getTouchY(int pointer);
     public float getAccelX();
     public float getAccelY();
     public float getAccelZ();
     public List<KeyEvent> getKeyEvents();
     public List<TouchEvent> getTouchEvents();
    }

What I don't get is that I thought that Java didn't allow interfaces to have fields. Is this different for android run Java?

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • 1
    The fields aren't directly in the interface; they're in nested static classes within the interface. Interfaces allow nested static classes, and classes allow fields. – Silvio Mayolo Jun 14 '13 at 07:14

3 Answers3

0

It is possible, here's a link to the same question but for Java, not Android specific.

inner class within Interface

Community
  • 1
  • 1
Martin
  • 3,018
  • 1
  • 26
  • 45
0

It's not uncommon to find interfaces with fields defined, when you implement the interface the implementation will inherit the fields from the interface.

Philio
  • 3,675
  • 1
  • 23
  • 33
0

Rule of thumb for Interface in Java:

  1. Must only include abstract methods and final fields
  2. Cannot be used as base class

Therefore it can still include field, but it must be final. However, take note that Interface can also include inner class, which allows creation of any type of field.

Arif Samin
  • 257
  • 1
  • 9
  • Thank you. I didn't mess with interfaces much in my classes as I preferred to just use Classes when possible and only used ever predefined interfaces. – Zack Malcire Jun 14 '13 at 08:29
  • you're welcome. regarding your practice, someday you will have to create your own interface to be utilized by functions such as callbacks. hence, like it or not you at least have to understand the basic. – Arif Samin Jun 14 '13 at 10:25