Class vs. Interface

后端 未结 10 1465
孤城傲影
孤城傲影 2020-12-10 03:18

I have a quite basic question:

When should we decide to use Interface or Class for a specific class?

For example: says we have 2 classes, Customer and Doctor

10条回答
  •  眼角桃花
    2020-12-10 03:42

    First thing to remember, Classes can be instantiated, Interfaces cannot.

    Secondly, a Class can only extend ONE Class. Interfaces are not limited by this and so we can have multiple inheritance like so

    public class foo extends Person implements Man, Mammal
    

    foo is a Person. It is also a Man and a Mammal;

    The only issue is Interfaces cannot have variables or method implementations where as a class(or abstract class for that matter) can.

    Generally I would say stick with interfaces and avoid abstract classes if you can.

提交回复
热议问题