1. 成员区别
- 抽象类 变量 常量;有构造方法,有抽象方法,也有非抽象方法
- 接口 常量,抽象方法(JDK8 在接口中定义 非抽象方法)
2. 关系区别
- 类与类 继承单继承
- 类与接口 实现,单实现和多实现
- 接口与接口 继承,单继承和多继承
3. 设计区别
- 抽象类 对类抽象,包括属性行为(对事物的抽象)
- 接口 对行为抽象,主要是行为(对行为的抽象)
下面举例子说明 3.设计区别
例子:门和报警器,将门设为抽象类
行为:关门 开门 报警
门的品牌——PanPan门 MeiXin门 ...
不是所有的品牌门 都带 报警
比如 PanPan门 关门 开门 报警
MeiXin门 关门 开门 没有报警
门——抽象类
案例代码:
Door.java
package com.面向对象.Demo32;public abstract class Door {private String name;private int height;private int widht;public Door(String name, int height, int widht) {this.name = name;this.height = height;this.widht = widht;}public String getName() {return name;}public int getHeight() {return height;}public int getWidht() {return widht;}public abstract void open(); //开门public abstract void close();//关门
}
Alarm.java
package com.面向对象.Demo32;public interface Alarm { //报警接口void alarm();//报警功能
}
PanPanDoor.java
package com.面向对象.Demo32;public class PanPanDoor extends Door implements Alarm {public PanPanDoor(String name, int height, int widht) {super(name, height, widht);}@Overridepublic void open() {System.out.println("PanPanDoor-open()");}@Overridepublic void close() {System.out.println("PanPanDoor-close()");}@Overridepublic void alarm() {System.out.println("PanPanDoor-alarm()");}
}
MenXin.java
package com.面向对象.Demo32;public class MenXin extends Door{public MenXin(String name, int height, int widht) {super(name, height, widht);}@Overridepublic void open() {System.out.println("MeiXin-open()");}@Overridepublic void close() {System.out.println("MenXin-close()");}
}
Test01.java
package com.面向对象.Demo32;public class Test01 {public static void main(String[] args) {MenXin meiXinDoor = new MenXin("MeiXinDoor", 175, 300);System.out.println(meiXinDoor.getName() + "," + meiXinDoor.getHeight() + "," + meiXinDoor.getWidht());meiXinDoor.open();meiXinDoor.close();System.out.println("===================");PanPanDoor panPanDoor = new PanPanDoor("PanPanDoor", 280, 175);System.out.println(panPanDoor.getName() + "," + panPanDoor.getHeight() + "," + panPanDoor.getWidht());panPanDoor.open();panPanDoor.close();panPanDoor.alarm();}
}
下一篇文章: