Java抽象类&接口(intergace)到底有什么区别

前言

1、在Java中 ,实现抽象类的机制有两种:抽象类(abstract class)和接口(interface).

2、两者非常相似,甚至可以相互可以相互替换,因此很多的开发者对于二者的选择上非常的随意,其实,二者的开发区别还是很大的。

目录

1240

1、知识储备:抽象是什么

1240

2、抽象类的两种实现方式

1240

抽象类示例

// 定义1抽象动物类Animal,提供抽象方法 = cry()
public abstract class Animal {  
    public abstract void cry();  
}  

// 猫、狗 = 动物类的子类
// 由于cry()为抽象方法,所以Cat、Dog必须要实现cry()
public class Cat extends Animal{  

    @Override  
    public void cry() {  
        System.out.println("猫叫:喵喵...");  
    }  
}  

public class Dog extends Animal{  

    @Override  
    public void cry() {  
        System.out.println("狗叫:汪汪...");  
    }  

}  

// 测试
public class Test {  

    public static void main(String[] args) {  
        Animal a1 = new Cat();  
        Animal a2 = new Dog();  

        a1.cry();  
        a2.cry();  
    }  
}  

// 运行结果
猫叫:喵喵...  
狗叫:汪汪

3、接口

1240

示例:

interface Demo{

void method1();

void method2();

}

class Test implements Demo{

void method1();

void method2();

}

四、二者的区别

1240

五、实例讲解

下面的实例,可以更好的去理解关于接口和抽象类的使用

5.1.需求描述:

需求一:有一类门,基本功能有开门和关门

需求二:有一类门,基于上面的需求增加了报警器功能。

5.2需求实现:该需求的实现方式有三种

 1、只使用抽象类  2、只使用接口  3、同时使用抽象类和接口

示例:

// 方案1:只使用抽象类
  abstract class Door{  
      abstract void open();  
      abstract void close();  
      abstract void alarm();  
  }  

  // 具体使用时
  class AlarmDoor extends Door {  
      void open(){}  
      void close(){}  
      void alarm(){}  
  } 

// 方案2:只使用接口
  interface Door{  
      void open();  
      void close();  
      void alarm();  
  }  

  // 具体使用时
  class AlarmDoor implements  Door {  
      void open(){}  
      void close(){}  
      void alarm(){}  
  } 


// 方案3:同时使用抽象类 & 接口
  // 对于需求1 = 抽象1类事物,即 使用抽象类
  abstract class Door{  
      abstract void open();  
      abstract void close();  
  }  

  // 对于需求2 = 抽象事物中的某个行为, 即 使用 接口
  interface Alarm{  
      void alarm();  
  }  

  // 具体使用时
  class AlarmDoor extends Door implements Alarm{  
      void open(){}  
      void close(){}  
      void alarm(){}  
  } 

 


转载于:https://my.oschina.net/u/4034553/blog/3033047

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值