Skip to content

Instantly share code, notes, and snippets.

Created June 8, 2012 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/2894142 to your computer and use it in GitHub Desktop.
Save anonymous/2894142 to your computer and use it in GitHub Desktop.
インタフェースのサンプルコード
/**
* 「運転する」事を抽象化したインタフェース
*/
public interface Drivable{
// コンパイル通るのか???
int a = 5;
// これはアウト
// int b;
// 発進!
public void start();
}
//////////////////////////////////////////////////////////////
/**
* 「レースをする」事を抽象化したインタフェース
*/
public interface Racable{
// 発進!
public void start();
}
//////////////////////////////////////////////////////////////
/**
* インタフェースの実装確認サンプルコード
*
*/
public class Cycle{
// 自転車発進!
public void start(){
System.out.println("自転車発進!");
b = 10;
}
// 自転車で曲がった!
public void turn(){
System.out.println("自転車で曲がった!");
}
}
//////////////////////////////////////////////////////////////
/**
* インタフェースの実装確認サンプルコード
*
*/
public class Train implements Drivable{
// 電車発進!
public void start(){
System.out.println("電車発進!");
b = 10;
}
// 電車停止!
public void stop(){
System.out.println("電車停止!");
}
}
//////////////////////////////////////////////////////////////
/**
* インタフェースの確認サンプルコード
*
*/
public class TestIFMain{
//
public static void main(String[] args){
// 自転車のインスタンス作成
Cycle c = new Cycle();
c.start();
c.turn();
c.stop();
//問1.すぐ下のコメントアウトを解除して、コンパイルエラーが発生しないように
// 「Cycle」クラスが「Drivable」インタフェースを実装するように修正して下さい
Drivable vehicle = new Cycle();
vehicle.start();
vehicle.stop();
vehicle.turn();
//問2.すぐ下のコメントアウトを解除してもエラーにならないように
// Cycleクラスについて、「Racable」インタフェースも実装するように修正して下さい
// Racable raceCycle = new Cycle();
// raceCycle.start();
//問3.すぐ下のコメントアウトを解除して、コンパイル結果・実行結果について確認して下さい。
// Drivable x = new Cycle();
// x.start();
// x = new Train();
// x.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment