Java创建对象的6种方式
发表于更新于
字数总计:483阅读时长:2分钟阅读量: 剑河
后端JavaJava创建对象的6种方式
苏泽Java创建对象的方式有几种?
1.通过new创建新对象
2.通过clone()
3.通过反射
4.使用反序列化
5.使用工厂模式
6.使用Builder模式
样例如下:
1 2
| Student stu1 = new Student(); stu1.show("1");
|
1 2
| Student stu2 = (Student)stu1.clone(); stu2.show("2")
|
1 2 3
| Class<Student> clazz = Stduent.class; Student stu3 = clazz.getDeclaredConstructor().newInstance(); stu3.show("3")
|
1 2 3 4
| String fileName = "绝对路径/Student.stu1"; ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName)); Student stu4 = (Student) in.readObject(); stu4.show("4");
|
1 2 3 4 5 6 7 8 9
| Student stu5 = Student.createInstance(); stu5.show("5");
class Student{ public static Student createInstance(){ return new Studnet(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| Student stu6 = new Student.Builer().setName("hhh").build(); stu6.show("6");
class Student{ static class Builder{ private String name; public Builder setName(String name){ this.name = name; return this; } public Student build(){ return Student(this); } } }
|
了解什么是静态内部类
定义在一个类内部的静态类,需要使用static来修饰,
可以访问外部类的静态成员
可以使用自己的构造器
构造函数
1.初始化对象状态
2.创建对象实例
了解这些后 总结以下
1.创建对象的六种方式
2.以及创建每个对象需要知道的知识
3.静态内部类,构造函数
4.以及反序列化使用的out in,输出输入流,
1 2 3 4 5 6 7 8 9 10 11 12
| Student stuent = new Studnet(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName)) out.writerObject(student) 在进行读取 使用try-with-resources 自动关闭资源 不过使用中的类需要实现AutoCloseable接口否则编译不通过。 try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName))){ Student stu6 = in.readObject(); stu6.show("6"); }catch(IOExaction ex){ throw ex; }
|
总结
6个创建对象的方式。需要掌握基础知识。