Attributes / member variables in interfaces?

前端 未结 7 1426
眼角桃花
眼角桃花 2020-12-04 14:09

I wish to know is there any way in which I can make it compulsory for the implementer class to declare the objects handles/primitives as they do with methods. for e.g.:

7条回答
  •  醉梦人生
    2020-12-04 14:39

    The point of an interface is to specify the public API. An interface has no state. Any variables that you create are really constants (so be careful about making mutable objects in interfaces).

    Basically an interface says here are all of the methods that a class that implements it must support. It probably would have been better if the creators of Java had not allowed constants in interfaces, but too late to get rid of that now (and there are some cases where constants are sensible in interfaces).

    Because you are just specifying what methods have to be implemented there is no idea of state (no instance variables). If you want to require that every class has a certain variable you need to use an abstract class.

    Finally, you should, generally speaking, not use public variables, so the idea of putting variables into an interface is a bad idea to begin with.

    Short answer - you can't do what you want because it is "wrong" in Java.

    Edit:

    class Tile 
        implements Rectangle 
    {
        private int height;
        private int width;
    
         @Override
        public int getHeight() {
            return height;
        }
    
        @Override
        public int getWidth() {
            return width;
        }
    
        @Override
        public void setHeight(int h) {
            height = h;
        }
    
        @Override
        public void setWidth(int w) { 
            width = w;  
        }
    }
    

    an alternative version would be:

    abstract class AbstractRectangle 
        implements Rectangle 
    {
        private int height;
        private int width;
    
         @Override
        public int getHeight() {
            return height;
        }
    
        @Override
        public int getWidth() {
            return width;
        }
    
        @Override
        public void setHeight(int h) {
            height = h;
        }
    
        @Override
        public void setWidth(int w) { 
            width = w;  
        }
    }
    
    class Tile 
        extends AbstractRectangle 
    {
    }
    

提交回复
热议问题