Java中是否可以用接口替代抽象类?
或者说:抽象类有什么存在的价值?

解决方案 »

  1.   

    楼上各位说的都是些“实现上的区别”,其本质体现在设计思想……接口和抽象类是java实现抽象类(此处为泛指)的两种机制
    抽象类:体现的是一种继承关系,可以理解为“是什么”
    接口:体现为一种实现关系,可以理解为“实现了什么”
      

  2.   

    刚好也看到这里,书上有一个很好的例子:
    关于抽象类,FullTime和PartTime继承抽象类Employee,每本书上必有的例子,这个大家应该都很熟悉了
    关于接口,Payroll实现Payable接口,只能调用和员工薪水有关的方法;HumanResources实现EmployeeInfo接口,只能调用员工信息有关方法
    public abstract class Employee implements Payable, EmployeeInfo
    {
    private String name, address;
            private double weeklyPay; public Employee(String name, String address)
    {
    this.name = name;
    this.address = address;
    } public String getName()
    {
    return name;
    } public void setName(String n)
    {
    name = n;
    } public String getAddress()
    {
    return address;
    } public void setAddress(String a)
    {
    address = a;
    } public double getWeeklyPay()
    {
    return weeklyPay;
    } public void computePay(int hoursWorked)
    {
    weeklyPay = hoursWorked * 6.50;
    System.out.println("Weekly pay for " + name + " is $" + weeklyPay);
    } public void mailCheck()
    {
    System.out.println("Mailing check to " + name + " at " + address);
    }
    }public interface Payable
    {
    public void computePay(int hoursWorked);
    public void mailCheck();
    public double getWeeklyPay();
    }public interface EmployeeInfo
    {
    public String getName();
    public void setName(String n);
    public String getAddress();
    public void setAddress(String a);
    }public class Payroll
    {
    public void payEmployee(Payable p)
    {
    p.computePay(40);
    p.mailCheck();
    } public void printPaycheck(Payable p)
    {
    System.out.println("Printing check for $" + p.getWeeklyPay());
    }
    }public class HumanResources
    {
    public String getInfo(EmployeeInfo e)
    {
    return e.getName() + " " + e.getAddress();
    } public void changeName(EmployeeInfo e, String name)
    {
    System.out.println("Changing name for " + e.getName());
    e.setName(name);
    System.out.println("New name is " + e.getName());
    } public void updateAddress(EmployeeInfo e, String address)
    {
    System.out.println("Changing address for " + e.getName());
    e.setAddress(address);
    System.out.println("New address is " + e.getAddress()); }
    }