100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Android什么时候用抽象类什么时候用接口

Android什么时候用抽象类什么时候用接口

时间:2022-07-04 06:46:25

相关推荐

Android什么时候用抽象类什么时候用接口

什么时候使用抽象类和接口?

抽象类 :本类固有的属性和行为(共享抽象类核心属性和行为时)

接口: 扩展功能的时候 (当类共享外围行为时,就会使用接口)

举个例子

飞行员是抽象类

f16飞行员 具体类

安全员 接口

所以在写f16飞行员类的时候,你需要写关于飞行员的公共类的时候你用抽象类,当你需要写关于f16飞行员本类不属于共有的属性特性的时候(共有的如都需要训练,都有一个隶属的单位如美国空军,不是共有的安全员,麦霸)用接口。

再举个栗子

继承 is a 是基本功能

接口 like a 是额外功能

比如某个机构培训的学员,学员都有学习工功能(基本功能),抽烟则是额外功能(有些学员是不抽烟的)

所以你写学员这个类的时候,你可以继承公共的类中的学习方法,你如果想继承抽烟那你用接口(抽烟不是基本功能)

stack overFlow上的解释

How about an analogy: when I was in the Air Force, I went to pilot training and became a USAF (US Air Force) pilot. At that point I wasn’t qualified to fly anything, and had to attend aircraft type training. Once I qualified, I was a pilot (Abstract class) and a C-141 pilot (concrete class). At one of my assignments, I was given an additional duty: Safety Officer. Now I was still a pilot and a C-141 pilot, but I also performed Safety Officer duties (I implemented ISafetyOfficer, so to speak). A pilot wasn’t required to be a safety officer, other people could have done it as well.

All USAF pilots have to follow certain Air Force-wide regulations, and all C-141 (or F-16, or T-38) pilots ‘are’ USAF pilots. Anyone can be a safety officer. So, to summarize:

Pilot: abstract class

C-141 Pilot: concrete class

ISafety Officer: interface

added note: this was meant to be an analogy to help explain the concept, not a coding recommendation. See the various comments below, the discussion is interesting.

比方说,当我在空军服役时,我参加了飞行员训练,后来成为美国空军(美国空军)飞行员。那时我没有资格飞任何东西,必须参加飞机类型的训练。一旦我合格,我就成了飞行员(抽象类)和c-141飞行员(具体的班级)。在我的一次作业中,我被赋予了额外的职责:安全官员。现在我仍然是一名飞行员和c-141飞行员,但我也执行了安全官员职责(可以说是我执行了isaf机长)。飞行员不需要成为一名安全官员,其他人也可以这样做。

所有美国空军飞行员都必须遵守某些空军的规定,所有的c-141(或f16,或t-38)飞行员都是美国空军飞行员。任何人都可以成为安全官员。所以,总结一下:

飞行员:抽象类

c - 141飞行员:具体类

ISafety官员:接口

补充说明:这是一个比喻来帮助解释概念,而不是编码建议。参见下面的各种评论,讨论很有趣。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。