接口
一、抽象类和抽象方法
抽象方法:仅有声明而没有方法体
抽象类:包含抽象方法的类。(如果一个类包含一个或者多个抽象方法,该类必须被限定为抽象的)。
二、java中的多重继承----(继承一个类,实现多个接口)
顺序:先继承类,后实现接口
方式:要从一个非接口的类继承,只能从一个类去继承。其余元素都必须是接口,
需要将所有的接口名都置于implements关键字之后,用逗号将它们一一隔开。
使用接口的核心原因:
①为了向上转型为多个基类型(以及游戏带来的灵活性)
②与使用抽象基类相同:防止客户端程序员创建该类的对象,并确保这仅仅是建立一个接口。
三、接口与工厂
import static net.mindview.util.Print.*;
//两个接口
interface Game {boolean move();}
interface GameFactory{Game getGame();}
class Checkers implements Game{
private int moves =0;
private static final int MOVES =3;
public boolean move(){
print("Checkers move "+moves);
return ++moves != MOVES;
}
}
class CherkersFactory implements GameFactory{
public Game getGame(){
return new Checkers();
}
}
class Chess implements Game{
private int moves =0;
private static final int MOVES =4;
public boolean move(){
print("Chess move "+moves);
return ++moves != MOVES;
}
}
class ChessFactory implements GameFactory{
public Game getGame(){ return new Chess();}
}
public class Games{
public static void playGame(GameFactory factory){
Game s =factory.getGame();
while(s.move())
;
}
public static void main(String[] args){
playGame(new CheckersFactory());
playGame(new ChessFactory());
}
}
//output
Checkers move 0
Checkers move 1
Checkers move 2
Chess move 0
Chess move 1
Chess move 2
Chess move 3

执行顺序:①②③④⑤⑥
解释:⑤⑥:普通接口及实现类
③④:工厂接口及实现类
②:定义工厂接口对象的方法,用于传参(工厂接口的实现类对象)
①:调用静态方法
网友评论