2013年12月28日 星期六

[Java 教學範例拷貝]- 抽象類別(Abstract class)

[Java 教學範例拷貝]- 抽象類別(Abstract class)


 


剛才找資料時發現一個的Java 教學網站,趕快發揮(C/P)的長才將它備份來,有需要的同好,歡迎來(C/P)一下^^。


 


拷貝來源:
http://openhome.cc/Gossip/JavaGossip-V1/


http://openhome.cc/Gossip/JavaGossip-V1/AbstractClass.htm


 









public abstract class AbstractGuessGame {
private int number;

public void setNumber(int number) {
this.number = number;
}

public void start() {
showMessage("Welcome");

int guess;
do {
guess = getUserInput();
if(guess > number) {
showMessage("bigger than the goal number");
}
else if(guess < number) {
showMessage("smaller than the goal number");
}
else
showMessage("you win");
} while(guess != number);
}

protected abstract void showMessage(String message);
protected abstract int getUserInput();
}
import java.util.Scanner;

public class ConcreteGuessGame extends AbstractGuessGame {
private Scanner scanner;

public ConcreteGuessGame() {
scanner = new Scanner(System.in);
}

protected void showMessage(String message) {
System.out.println(message + "!");
}

protected int getUserInput() {
System.out.print("input a number: ");
return scanner.nextInt();
}
}
public class Test {
public static void main(String[] args) {
AbstractGuessGame guessGame =
new ConcreteGuessGame();
guessGame.setNumber(50);
guessGame.start();
}
}


 


沒有留言:

張貼留言