1.interface与abstract的对比:
接口: 接口是比抽象类更纯粹的“抽象类”!里面所有成员变量默认static和final,所有方法都是隐式public且abstract,如果被implements了就必须实现所有方法!最后的是可以被“多继承”!
抽象类: 其实本质上抽象类的特性贴近于类,该能用的都能用!他的特点是:只要类中有一个方法是abstract的,这个类就是抽象类,但是反过来却并不一定(抽象类中可以有抽象方法和非抽象方法)!抽象类只能被单继承!
interface Instrument {
int time = 60; // static && final
void play(Node n); // public && abstract
}
class Wind implements Instrument{
public int time = 120;
public void play(Node n) {
System.out.println("Wind play " + n.toString());
}
}
class Percussion implements Instrument{
public void play(Node n) {
System.out.println("Percussion play " + n.toString());
}
}
class Stringed implements Instrument{
public void play(Node n) {
System.out.println("Stringed play " + n.toString());
}
}
class Music{
static void tune(Instrument i){
i.play(Node.B_FLAT);
}
static void tuneAll(Instrument[] is){
for (Instrument i: is){
tune(i);
}
}
public static void main(String[] args) {
Instrument[] is = {new Wind(), new Percussion(), new Stringed()};
tuneAll(is);
}
}
enum Node{
MIDDLE_C, C_SHARP, B_FLAT;
}
如果要创建不带任何方法定义和成员变量的基类,那么就选择接口而不是抽象类。
2.interface的“多继承”:
interface CanFly{
void fly();
}
interface CanFight{
void fight();
}
interface CanSwim{
void swim();
}
abstract class CanJump{
void jump(){
System.out.println("Hero can jump!");
}
}
class Hero extends CanJump implements CanFight, CanFly, CanSwim{
public void fly() {
System.out.println("Hero can fly!");
}
public void fight() {
System.out.println("Hero can fight!");
}
public void swim() {
System.out.println("Hero can swim!");
}
@Override
public void jump(){
super.jump();
}
}
public class Adventure{
static void swim(CanSwim s){
s.swim();
}
static void fight(CanFight f){
f.fight();
}
static void fly(CanFly f){
f.fly();
}
static void jump(CanJump j){
j.jump();
}
public static void main(String[] args) {
Hero hero = new Hero();
swim(hero);
fight(hero);
fly(hero);
jump(hero);
}
}
这里Hero类继承了CanJump并实现了三个接口CanFight, CanFly, CanSwim;需要注意的是接口需要放在后面!接口中的定义方法尽量不要太多,避免出现重复报错!
3.可以通过extends interface拓展interface:
interface CanBreath{
void breath();
}
interface CanWalk extends CanBreath{
void walk();
}
interface CanRun extends CanBreath, CanWalk{
void run();
}
class Runner implements CanRun{
public void breath() {
System.out.println("Runner is breathing!");
}
public void walk() {
System.out.println("Runner is walking!");
}
public void run() {
System.out.println("Runner is running!");
}
}
public class GoodDay{
static void start(CanRun r){
r.breath();
r.walk();
r.run();
}
public static void main(String[] args) {
Runner runner = new Runner();
start(runner);
}
}
4.interface中的域(成员变量):
因为接口中的所有成员变量都是static和final的,因此这些变量可以作为常量来使用。类似于枚举类型,直接创建几个变量直接使用即可。
因为是final类型,所以变量必须初始化。
因为是static类型,所以变量在类第一次加载是初始化。
后续保持更新…