• 关于工厂的应用——中国工人和美国工人的问题


     首先建立一个父类,包括中国和美国工人的属性以及方法

    1
    public abstract class TestEmployee { 2 String name; 3 int age; 4 String sex; 5 6 public TestEmployee() { 7 } 8 public TestEmployee(String name, int age, String sex) { 9 super(); 10 this.name = name; 11 this.age = age; 12 this.sex = sex; 13 } 14 15 public abstract void show();

     建立一个中国工人的子类,中间包括他特有的属性生肖,注意构造器的参数和父类顺序一致
     1 public class TestUSA extends TestEmployee {
     2     String xingzuo;
     3     
     4 
     5     public TestUSA() {
     6     }
     7 
     8     public TestUSA(String name, int age, String sex,String xingzuo) {
     9         super(name, age, sex);
    10         this.xingzuo=xingzuo;
    11     }
    12 
    13 
    14     @Override
    15     public void show() {
    16         System.out.println("姓名"+name);
    17         System.out.println("年龄"+age);
    18         System.out.println("性别"+sex);
    19         System.out.println("星座"+xingzuo);
    20         
    21     }
    22     
    23 
    24 }
    
    

    同理,建立美国工人的子类


    1
    public class TestChina extends TestEmployee { 2 String shengxiao; 3 4 public TestChina() { 5 } 6 7 public TestChina(String name,int age,String sex,String shengxiao) { 8 super(name,age,sex); 9 this.shengxiao = shengxiao; 10 } 11 12 @Override 13 public void show() { 14 System.out.println("姓名"+name); 15 System.out.println("年龄"+age); 16 System.out.println("性别"+sex); 17 System.out.println("生肖"+shengxiao); 18 } 19 20 }
     建立工厂,这里的方法名为getA,
    1
    import java.util.Scanner,TestEmployee为返回值类型(引用类型:引用),getA为方法名。在输入特又属性时利用equals进行判断,同时创建对象 2 3 public class TestEmployeeFactory { 4 public static TestEmployee getA(String str){ 5 Scanner input =new Scanner(System.in); 6 System.out.println("请输入姓名"); 7 String name=input.next(); 8 System.out.println("请输入年龄"); 9 int age=input.nextInt(); 10 System.out.println("请输入性别"); 11 String sex=input.next(); 12 13 TestEmployee emp=null; 14 if(str.equals("china")){ 15 System.out.println("请输入生肖"); 16 String shengxiao=input.next(); 17 emp=new TestChina(name,age,sex,shengxiao); 18 19 }else if(str.equals("usa")){ 20 System.out.println("请输入星座"); 21 String xingzuo=input.next(); 22 emp=new TestUSA(name,age,sex,xingzuo); 23 } 24 return emp; 25 } 26 27 public static void main(String[] args) { 28 TestEmployee emp1=getA("china"); 29 emp1.show(); 30 31 } 32 }
  • 相关阅读:
    【原生】数组去重的方法
    【原生】详解Javascript中prototype属性(推荐)
    【原生】 ES5中的构造函数与 ES6 中的类 及构造函数的理解
    【react】React学习:状态(State) 和 属性(Props)
    【react】 flux 了解
    【请求数据】fetch 的get请求和post请求
    【react】 使用create-react-app创建react项目,运行npm run eject报错: 暴露webpack配置文件
    package.json 文件的介绍
    802.11协议精读1:学习资料整理(转)
    ns2之包结构解析
  • 原文地址:https://www.cnblogs.com/hudada007/p/6713740.html
Copyright © 2020-2023  润新知