Created
June 8, 2012 07:11
-
-
Save anonymous/2894142 to your computer and use it in GitHub Desktop.
インタフェースのサンプルコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 「運転する」事を抽象化したインタフェース | |
*/ | |
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