zoukankan      html  css  js  c++  java
  • 关于工厂的应用——中国工人和美国工人的问题

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

    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 }
  • 相关阅读:
    学习redis-安装和基本一些命令
    Eclipse启动报错Java was started but returned exit code=13
    踩过的坑系列之InputStream.read(byte[])方法
    <<深入Java虚拟机>>-虚拟机类加载机制-学习笔记
    <<深入Java虚拟机>>-第三章-垃圾收集器与内存分配策略-学习笔记
    <<深入Java虚拟机>>-第二章-Java内存区域-学习笔记
    创建线程的两种方式比较Thread VS Runnable
    Java设计模式之--代理模式学习
    shell脚本中$参数的介绍
    (转)使用DataTime这个类来获取当前的时间
  • 原文地址:https://www.cnblogs.com/hudada007/p/6713740.html
Copyright © 2011-2022 走看看