On the way of creating objects in Java

Posted by designationlocutus on Fri, 11 Feb 2022 00:57:18 +0100

Four ways to create objects in Java

1. Create objects through new

Creating objects through new is the most common way in Java and the way we first learned to create objects. However, creating objects through new will increase the overall coupling degree. We should pay attention to the impact of coupling degree in our future programming life, so reducing coupling degree is something we must consider.

Not much to say, let's go to the code.

a. First create a class.

package com.tzz.test;

public class Hello {
    public void sayWorld(){
        System.out.println("Hello, world!");
    }
}

b. Create the object of the class through new and call its methods

package com.tzz.test;

public class NewHello {
    public static void main(String[] args) {
        Hello hello = new Hello();
        hello.sayWorld();
    }
}

2. Create objects through reflection mechanism

In the learning process of Java, reflection is our essential knowledge point. At present, we create objects through reflection. Of course, we mainly explain the knowledge point of creating objects through reflection, because reflection is an important knowledge point in Java. At present, there are no more knowledge points related to reflection.

a. Create through the newInstance method of Class class

At this time, the normal class Hello remains unchanged, and the code for creating the class is as follows

package com.tzz.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class NewHello {
    public static void main(String[] args) {
        try {
            Class newHello = Class.forName("com.tzz.test.Hello");
            Hello hello = (Heloo)newHello.newInstance();
            heloo.sayWorld();
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (IllegalAccessException e){
            e.printStackTrace();
       }catch (InstantiationException e){
            e.printStackTrace();
        }
    }
}

b. Use the new method of the instance class to create

The code is as follows:

package com.tzz.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class NewHello {
    public static void main(String[] args) {
        try {
            Class hello = Class.forName("com.tzz.test.Hello");
            Constructor constructor = heloo.getConstructor();
            Heloo hello1 = (Hello)constructor.newInstance();
            heloo1.sayWorld();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

3. Create an object through the clone method of the object

package com.tzz.test;

public class CloneHello implements Cloneable{
    public void sayhello(){
        System.out.println("Hello, world!");
    }

    public static void main(String[] args) {
        CloneHello cloneHello = new CloneHello();
        try {
            CloneHello cloneHello1 = (CloneHello)cloneHello.clone();
            cloneHello1.sayhello();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

4. Create objects by deserialization

We may have less knowledge about serialization and deserialization, but serialization knowledge occupies a great importance in the whole Java knowledge. We just briefly learn to create objects. For more knowledge of serialization and deserialization, we will explain it in more detail in the future.

Why are objects created by deserialization? As we all know, our computer space is divided into stacks and heaps, and our objects are all in heap space. However, our Java featured garbage collection mechanism (GC) recycling includes heap space. Once our objects are recycled, they will be destroyed, and our original objects will no longer exist. If we still need this object at this time, what can we do? Some students will say that if it's a big deal, I'll recreate it again, but the object we recreate is no longer our previous object. At this time, we can get the previous object through the reverse order class,. Why? Let's talk about serialization. Serialization is that objects are stored in our memory space and saved through input and output streams. Let's take a look at the relevant code

package com.tzz.test;
import java.io.*;

public class SerializeTest {
    Hello hello = new Hello();

    //Prepare a file for storage
    File file = new File("hello.obj");

    FileOutputStream fos;

    {
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    ObjectOutputStream oos;

    {
        try {
            oos = new ObjectOutputStream(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    FileInputStream fis;

    {
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    ObjectInputStream ois;

    {
        try {
            ois = new ObjectInputStream(fis);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
      
}

The above is my understanding of creating objects in Java. If there are deficiencies, please understand and point out. Thank you. Because this is the first time to write a blog, there are many shortcomings. If there are big guys who have suggestions, you are welcome to point out.

Topics: Java Back-end