Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

c# - Class vs. Interface

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.

In Inheritance (class): we could set these 2 classes to inherit from parent class Person.

Couldn't we do the same with Interface? Says we have InterfacePerson and have both Customer and Doctor implement the interface?

Thus, this lead to: when do we decide to use one over the other and vice versa?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • Read the wikipedia article

  • Read a book, then read the chapters about OOP again

  • In your example, Person should be a class, because it contains implementation details that are common to both a Doctor and a Customer.

  • interfaces don't have (and don't need) implementation details - they only denote what objects which implement them are doing. Not how. Why is this useful? Because when you are using the object you don't care how it's going to do its job.

Let's take a look at a simple example - there is an interfaces Comparable (in Java at least). It denotes that its implementors can be compared with each other. So you can have two classes:

class Doctor implements Comparable {..}

class Customer implements Comparable {..}

Now you can have a common method which takes any set of objects which implement Comparable and call comparable1.compareTo(comparable2), because you know they can perform comparison - it's denoted by their interface.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...