3 Replies Latest reply on Jul 2, 2007 1:59 AM by 3004

    Constructor in an Interface

    807600
      All fields in an Interface are implicitly final and static

      Now, i know final variables have to be initialised by the constructor, if not initialised in the definition

      So, why no allow a constructor for an interface just to initialize the final variables?
        • 1. Re: Constructor in an Interface
          807600
          You can set default values by doing something like the following:
          public final int finalInteger = 12345;
          There are no constructors in an interface because they are not objects, they are interfaces. I can't imagine why you would really need to set default values in an interface anyway as each class that implements that interface would be using it for different purposes and in different ways. You should just add code to set the values in the constructor of the class that implements it.
          • 2. Re: Constructor in an Interface
            807600
            anyway as each class that
            implements that interface would be using it for
            different purposes and in different ways. You should
            just add code to set the values in the constructor of
            the class that implements it.
            ok i tried this
              
            interface A
            {
                 int x;                    // error - final uninitialized
                 int y=5;               // error - final is reinitialised in Demo()
            }
            
            class Demo implements A
            {
                 Demo()
                 {
                      x = 10;
                      y = 10;
                 }
                 
                 public static void main(String args[])
                 {
                      Demo d = new Demo();
                      System.out.println(x);
                 }
            }
            • 3. Re: Constructor in an Interface
              3004
              Now, i know final variables have to be initialised by
              the constructor, if not initialised in the
              definition
              Not final static fields. Constructors should NOT be setting static fields.

              So, why no allow a constructor for an interface just
              to initialize the final variables?
              Because they're static.