Interfaces and Abstract classes confusion in Java with examples

后端 未结 7 932
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-25 13:55

I\'m having trouble understanding when to use an interface as opposed to an abstract class and vice versa. Also, I am confused when to extend an interface with another inter

7条回答
  •  失恋的感觉
    2020-12-25 14:38

    Your shape example is good. I look at it this way:

    You only have abstract classes when you have methods or member variables that are shared. For your example for Shape you've only got a single, unimplemented method. In that case always use an interface.

    Say you had an Animal class. Each Animal keeps track of how many limbs it has.

    public abstract class Animal
    {
        private int limbs;
        public Animal(int limbs)
        {
            this.limbs = limbs;
        }
    
        public int getLimbCount()
        {
            return this.limbs;
        }
    
        public abstract String makeNoise();
    }
    

    Because we need to keep track of how many limbs each animal has, it makes sense to have the member variable in the superclass. But each animal makes a different type of noise.

    So we need to make it an abstract class as we have member variables and implemented methods as well as abstract methods.

    For your second question, you need to ask yourself this.

    Is a Triangle always going to be a shape?

    If so, you need to have Triangle extend from the Shape interface.

    So in conclusion - with your first set of code examples, choose the interface. With the last set, choose the second way.

提交回复
热议问题