语法
// 抽象类
abstract class ClassName{}
// 抽象方法
abstract void f()
注意点
规则
用途
<!--接口类型可以使用包权限,但是方法默认为public-->
抽象类是抽象若干个类的共同点并用来继承,接口是在导出类中增加导出类需要的特殊方法
使用接口和抽象类的原因
依赖倒置原则(Dependecy-Inversion Principle):依赖于抽象。具体而言就是高层模块不依赖于底层模块,二者都同依赖于抽象;抽象不依赖于具体,具体依赖于抽象。
使用接口或抽象类的原因
接口
抽象类
实现
<!--被适配对象-->
public class Adaptee220V {
int output220V(){
return 220;}}
public class Adaptee110V {
int output110V(){
return 110;}}
<!--适配器-->
public class Adapter220V extends Adaptee220V implements Target {
@Override public int output5V() {
int v = super.output220V();
// 将电压进行转换的具体实现
int dst = v / 44;
return dst;
}
}
public class Adapter110V extends Adaptee110V implements Target {
@Override public int output5V() {
int v = super.output110V();
int dst = v / 22;
return dst;
}
}
<!--接口-->
public interface Target {
int output5V();
}
<!--使用类-->
public class Phone {
// 充电方法,充电需要用到供电方法
void charging(Target target){
int v = target.output5V();
System.out.println("使用成功,方法为"+target.getClass().getSimpleName()+",电压为:"+v);
}
}
<!--测试类-->
public class TestAdapter {
public static void main(String[] args) {
new Phone().charging(new Adapter220V());
new Phone().charging(new Adapter110V());
}
}
注意点:
扩展接口方法
接口使用extends引用多个基类接口;原因:类多重继承时,如果被继承类中存在相同方法则无法判断调用方法。接口允许多重继承,因为都是抽象方法
// 继承多个接口的接口
public interface Human extends CanJump,CanRun,CanSay {
void CanSleep();
}
public interface CanJump {
void jump();
void fastJump();
}
public interface CanRun {
void run();
void fastRun();
}
public interface CanSay {
void say();
void fastSay();
}
避免使用不同接口中使用相同的方法名
因此在java SE5之前存在使用接口域创建enum类型的变量
规则
规则
实现
<!--类嵌套接口-->
class A {
private interface D{
void f();
};
private class DImp implements D{
@Override public void f() {};
}
public class DImp2 implements D{
@Override public void f(){};
}
}
<!--接口嵌套接口-->
interface A{
// 接口默认是abstract,不能是private,因为接口中元素只能是public
//public abstract interface B{
interface B{
public static final int num = 50;
}
<!--接口嵌套类-->
interface C{
class D{
}
}
实现
<!--接口-->
// 接口
public interface Game {
void play();
}
// 工厂接口
public interface GameFactory {
Game getGame();
}
<!--实现类-->
// 硬币游戏类
class CoinGame implements Game{
@Override public void play() {
System.out.println("This is coin game");
}
}
// 骰子游戏类
public class DiceGame implements Game{
@Override public void play() {
System.out.println("This is dice game");
}
}
// 工厂类
public class GameFactoryCoin implements GameFactory {
@Override public Game getGame() {
return new CoinGame();
}
}
public class GameFactoryDice implements GameFactory {
@Override public Game getGame() {
return new DiceGame();
}
}
<!--测试类-->
public class Test19 {
// 传入工厂对象
static void playGame(GameFactory gameFactory){
Game game = gameFactory.getGame();
game.play();
}
public static void main(String[] args) {
playGame(new GameFactoryCoin());
playGame(new GameFactoryDice());
}
}