Understanding how to create and initialize objects in java-4.1 from scratch
This section describes how to create and initialize objects.
The problem that needs to be discussed comes from the C language. In C language, a lot of errors are caused by forgetting to initialize some things. He needs to complete two operations-create and initialize to use the library construction, however, in java, constructor is used to create and initialize the object, which is the same, so some initialization errors are avoided.
package com.ray.testobject;public class Test {public static void main(String[] args) {TestClass t1=new TestClass();TestClass t2=new TestClass();}}class TestClass {public TestClass() {System.out.println(TestClass created);}public TestClass(int param) {System.out.println(TestClass created);System.out.println(param);}}
Output:
TestClass created
TestClass created
1
From the output results, we can see that when creating an object, we can use the constructor to further initialize the object without the need for specific initialization functions.
If the constructor does not input any parameters, an object without any attributes will be created.
It should be noted that even if we do not initialize the object property, the compiler will initialize it for us, so as to reduce certain errors.
Let's modify the above Code:
Package com. ray. testobject; public class Test {public static void main (String [] args) {TestClass t1 = new TestClass (); TestClass t2 = new TestClass (1 );}} class TestClass {private String name; // Add the private int id property; // Add the public TestClass () {System. out. println (TestClass created); System. out. println (id); System. out. println (name);} public TestClass (int param) {System. out. println (TestClass created); System. out. println (param); System. out. println (id); System. out. println (name );}}
Output:
TestClass created
0
Null
TestClass created
1
0
Null
As you can see from the output, the object has initialized its attributes during initialization.
Let's modify the program to see how the parameters initialized by the constructor differ from those initialized by the object.
Package com. ray. testobject; public class Test {public static void main (String [] args) {TestClass t1 = new TestClass (); TestClass t2 = new TestClass (1 );}} class TestClass {private String name; public TestClass () {System. out. println (TestClass created); System. out. println (name);} public TestClass (String param) {// modified the param type System. out. println (TestClass created); System. out. println (param); System. out. println (name );}}
Output:
TestClass created
Null
TestClass created
1
Null
If you need to use the param constructor to construct an object, you must initialize param. Therefore, param is the setting that you think, and name is the attribute field, which is automatically initialized by the compiler.
Summary: This chapter discusses some topics about object creation and initialization.