Java创建对象的5种方式

实现

package com.mikamo.newclass;

import java.io.Serializable;

public class Employee implements  Serializable {

    private static final long serialVersionUID = -2237531491283515012L;

    private String name;

    public Employee() {

    }

    public Employee(String name) {
        this.name = name;
    }

    public void show(){
        if(name != null){
            System.out.println(name);
        }else{
            System.out.println("employee");
        }
    }

    @Override
    protected Employee clone() throws CloneNotSupportedException {
        return this;
    }
}
package com.mikamo.newclass;

import java.io.*;
import java.lang.reflect.Constructor;

public class Test {

    public static void main(String[] args){
        try {
            //使用new关键字构造
            Employee e1 = new Employee();
            e1.show();
            System.out.println("------------------------------------------");
            //只能通过无参构成方法构造
            Employee e2 = Employee.class.newInstance();
            e2.show();
            System.out.println("------------------------------------------");
            //获取指定的构成方法
            Constructor<Employee> constructor = Employee.class.getConstructor(String.class);
            Employee e3 = constructor.newInstance("luke");
            e3.show();
            System.out.println("------------------------------------------");
            //通过实现clone方法克隆对象
            Employee e4 = e3.clone();
            e4.show();
            System.out.println("------------------------------------------");
            //通过序列化对象写入到文件,和反序列化读取对象
            ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("D:/employee.txt")));
            oo.writeObject(e1);
            oo.close();
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("D:/employee.txt")));
            Employee e5 = (Employee)ois.readObject();
            ois.close();
            e5.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

结果

employee
------------------------------------------
employee
------------------------------------------
luke
------------------------------------------
luke
------------------------------------------
employee

参考

https://mp.weixin.qq.com/s/3u7dTh-TLA8fVlRvfw9BaA

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值