NO. | 区别点 | 抽象类 | 接口 |
---|---|---|---|
1 | 定义 | 包含一个抽象方法的类 | 抽象方法和全局变量的集合 |
2 | 组成 | 构造方法,抽象方法,普通方法,常量, 变量 | 常量,抽象方法 |
3 | 关系 | 抽象了可以使用多个接口 | 接口不能继承抽象类,但允许继承多个接口 |
4 | 使用 | 子类继承抽象类(extents) | 子类实现接口(implements) |
5 | 常见设计模式 | 模板设计 | 工厂设计,代理设计 |
7 | 局限 | 抽象类有单继承的局限 | 接口没有此局限 |
8 | 实际 | 作为一个模板 | 作为一个标准或表示一种能力 |
9 | 对象 | 通过对象多态性产生实例化对象 | 通过对象多态性产生实例化对象 |
10 | 选择 | 如果抽象类和接口都可以使用的话,优先使用接口,因为避免单继承局限 | 如果抽象类和接口都可以使用的话,优先使用接口,因为避免单继承局限 |
11 | 特殊 | 一个抽象类中可以包含多个接口,一个接口中可以包含多个抽象类 | 一个抽象类中可以包含多个接口,一个接口中可以包含多个抽象类 |
模板类例子
abstract class Person{
private String name ; // 定义name属性
private int age ; // 定义age属性
public Person(String name,int age){
this.name = name ;
this.age = age ;
}
public String getName(){
return this.name ;
}
public int getAge(){
return this.age ;
}
public void say(){ // 人说话是一个具体的功能
System.out.println(this.getContent()) ; // 输出内容
}
public abstract String getContent() ; // 说话的内容由子类决定
};
class Student extends Person{
private float score ;
public Student(String name,int age,float score){
super(name,age) ; // 调用父类中的构造方法
this.score = score ;
}
public String getContent(){
return "学生信息 --> 姓名:" + super.getName() +
";年龄:" + super.getAge() +
";成绩:" + this.score ;
}
};
class Worker extends Person{
private float salary ;
public Worker(String name,int age,float salary){
super(name,age) ; // 调用父类中的构造方法
this.salary = salary ;
}
public String getContent(){
return "工人信息 --> 姓名:" + super.getName() +
";年龄:" + super.getAge() +
";工资:" + this.salary ;
}
};
public class AbstractCaseDemo02{
public static void main(String args[]){
Person per1 = null ; // 声明Person对象
Person per2 = null ; // 声明Person对象
per1 = new Student("张三",20,99.0f) ; // 学生是一个人
per2 = new Worker("李四",30,3000.0f) ; // 工人是一个人
per1.say() ; // 学生说学生的话
per2.say() ; // 工人说工人的话
}
};
工厂类
interface Fruit{ // 定义一个水果接口
public void eat() ; // 吃水果
}
class Apple implements Fruit{
public void eat(){
System.out.println("** 吃苹果。") ;
}
};
class Orange implements Fruit{
public void eat(){
System.out.println("** 吃橘子。") ;
}
};
class Factory{ // 定义工厂类
public static Fruit getInstance(String className){
Fruit f = null ;
if("apple".equals(className)){ // 判断是否要的是苹果的子类
f = new Apple() ;
}
if("orange".equals(className)){ // 判断是否要的是橘子的子类
f = new Orange() ;
}
return f ;
}
};
public class InterfaceCaseDemo04{
public static void main(String args[]){
Fruit f = Factory.getInstance(null) ; // 实例化接口
f.eat() ;
}
};
代理类
interface Network{
public void browse() ; // 浏览
}
class Real implements Network{
public void browse(){
System.out.println("上网浏览信息") ;
}
};
class Proxy implements Network{
private Network network ; // 代理对象
public Proxy(Network network){
this.network = network ;
}
public void check(){
System.out.println("检查用户是否合法。") ;
}
public void browse(){
this.check() ;
this.network.browse() ; // 调用真实的主题操作
}
};
public class ProxyDemo{
public static void main(String args[]){
Network net = null ;
net = new Proxy(new Real()) ;// 指定代理操作
net.browse() ; // 客户只关心上网浏览一个操作
}
};