Interfaces and Abstract classes confusion in Java with examples

后端 未结 7 931
佛祖请我去吃肉
佛祖请我去吃肉 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:27

    Remember the basic concept when using abstract classes or interfaces.

    Abstract classes are used when class to extended is more closely coupled to the class implementing it, i.e when both have a parent-child relation.

    In example:

           abstract class Dog {}
    
           class Breed1 extends Dog {}
    
           class Breed2 extends Dog {}
    

    Breed1 and Breed2 are both types of a dog and has some common behavior as a dog.

    Whereas, an interface is used when implementing class has a feature it can take from the class to implemented.

         interface Animal {
             void eat();
             void noise();
         }
    
         class Tiger implements Animal {}
    
         class Dog  implements Animal {}
    

    Tiger and Dog are two different category but both eat and make noises ,which are different. So they can use eat and noise from Animal.

提交回复
热议问题