1、利用介面實現動態的建立物件[選做題] 1.1 建立4個類: 蘋果 香蕉 葡萄 園丁 1.2 在三種水果的構造方法中列印一句話. 以蘋果類為例
阿新 • • 發佈:2018-12-17
package javademo9;
import java.util.Scanner;
interface Fruit{
}
class Apple implements Fruit {
public Apple() {
System.out.println("建立了一個蘋果物件");
}
}
class Pear implements Fruit {
public Pear() {
System.out.println("建立了一個梨物件");
}
}
class Orange implements Fruit {
public Orange() {
System.out.println("建立了一個桔子物件");
}
}
//介面作為方法返回值的意義:返回實現了該介面的物件
class Gardener{
public Fruit create() {
Scanner input = new Scanner(System.in);
String name = input.next();
Fruit fruit = null;
switch(name){
case "蘋果":
fruit = new Apple();
break;
case "梨":
fruit = new Pear ();
break;
case "桔子":
fruit = new Orange();
break;
}
input.close();
return fruit;
}
}
public class Test1 {
public static void main(String[] args) {
Gardener g = new Gardener();
g.create();
}
}