Java第十七次作业
利用接口实现动态的创建对象:(知识点:接口 )
(1)创建4个类
1苹果
2香蕉
3葡萄
4园丁
(2)在三种水果的构造方法中打印一句话.
以苹果类为例
class apple
{
public apple()
{
System.out.println(“创建了一个苹果类的对象”);
}
}
(3)要求从控制台输入一个字符串,根据字符串的值来判断创建三种水果中哪个类的对象。
1 package date521; 2 3 interface Fruit { 4 5 } 6 7 class Apple implements Fruit { 8 public Apple() { 9 System.out.println("创建了一个苹果类的对象"); 10 } 11 }
1 package date521; 2 3 class Banana implements Fruit { 4 public Banana() { 5 System.out.println("创建了一个香蕉类的对象"); 6 } 7 }
1 package date521; 2 3 class Grape implements Fruit { 4 public Grape() { 5 System.out.println("创建了一个葡萄类的对象"); 6 } 7 }
1 package date521; 2 3 import java.util.Scanner; 4 5 public class Gardener { 6 public Fruit create() { 7 Scanner input = new Scanner(System.in); 8 String name = input.next(); 9 Fruit fruit = null; 10 11 switch (name) { 12 case "苹果": 13 fruit = new Apple(); 14 break; 15 case "香蕉": 16 fruit = new Banana(); 17 break; 18 case "葡萄": 19 fruit = new Grape(); 20 break; 21 } 22 input.close(); 23 return fruit; 24 25 } 26 27 }
1 package date521; 2 3 public class Text { 4 public static void main(String[] args) { 5 6 Gardener g = new Gardener(); 7 g.create(); 8 } 9 }

浙公网安备 33010602011771号