"Java from small white to Daniel" in the 11th chapter of the object

Source: Internet
Author: User
Tags garbage collection instance method

"Java from small white to Daniel" paper version has been shelves!!!

Class instantiation generates an object, an instance method is an object method, and an instance variable is an object property. The life cycle of an object consists of three stages: creation, use, and destruction. How much of the previous chapter has been used for objects, this chapter details the creation and destruction of objects and other related knowledge.

Creating objects

Creating objects consists of two steps: Declaration and instantiation.

1. Disclaimer

There is no difference between declaring an object and declaring a normal variable, with the following syntax:

type objectName;

Where type is a reference type, that is, a class, an interface, and an array. The sample code is as follows:

String name;

The statement declares a string type object name. You can declare that you do not allocate memory space to an object, but simply assign a reference.

2. Instantiation

The instantiation process is divided into two stages: allocating memory space and initializing objects for an object, first allocating memory space for the object using the new operator, and then invoking the constructor method to initialize the object. The sample code is as follows:

String name;name = new String("Hello World");

The string ("Hello World") expression in the code is the constructor that calls the string. After initialization is complete, 11-1 is shown.

Empty Object

A reference variable does not allocate memory space through new, which is an empty object, and Java uses the keyword NULL to represent an empty object. The sample code is as follows:

String name = null;name = "Hello World";

The reference variable default value is null. When attempting to invoke an instance variable or an instance method of an empty object, a null pointer exception NullPointerException is thrown, as shown in the following code:

String name = null;//输出null字符串System.out.println(name);//调用length()方法int len = name.length(); ①

However, the system throws an exception when the code runs to the ① row. This is because the name is an empty object when the length () method is called. Programmers should avoid calling the Null object's member variables and methods, the code is as follows:

//判断对象是否为nullif (name != null) {int len = name.length();}

Tip There are two possibilities for creating an empty object: The first is that the programmer forgets the instantiation himself, and the second is that the empty object is passed on to us by others. The first programmer must prevent this from happening, and you should examine your code carefully to instantiate and initialize all the objects that you have created. The second case needs to be avoided by judging the object's non-null.

Construction Method

In section 11.1, the expression new string ("Hello World") is used, where String ("Hello World") is called to construct the method. The constructor method is a special method in the class that initializes the instance variable of the class, which is the constructor method, which is called automatically after the object is created (the new operator).

Features of the Java construction method:

    1. The constructor method name must be the same as the class name.
    2. The constructor method does not have any return values, including void.
    3. The construction method can only be used in conjunction with the new operator.

The Construction method sample code is as follows:

//Rectangle.java文件package com.a51work6;// 矩形类public class Rectangle {// 矩形宽度int width;// 矩形高度int height;// 矩形面积int area;// 构造方法public Rectangle(int w, int h) { ①width = w;height = h;area = getArea(w, h);}...}

The code, ①, declares a construction method with two parameters W and H, which is used to initialize the two member variables of the rectangle object, width and height, and note that there are no previous return values.

Default constructor method {#-0}

Sometimes there is no construction method at all in the class. For example, the user class code in this section is as follows:

//User.java文件package com.a51work6;public class User {// 用户名private String username;// 用户密码private String password;}

From the user class code above, there are only two member variables, no construction method is seen, but you can still call the parameterless construction method to create the user object, see the following code.

//HelloWorld.java文件...User user = new User();

A Java virtual machine is a class that does not have a constructor method, and provides a default constructor method with no arguments, and the default constructor method has no statements in its method body, and the default constructor method is equivalent to the following code:

//默认构造方法public User() {}

The default constructor method has no statements in the body and cannot initialize member variables, so the member variables use default values, and the member variable defaults are related to the data type, as shown in table 9-1 in section 9.1.2. Don't repeat it here.

Constructor method overload {#-1}

There can be more than one constructor in a class, they have the same name (same as the class name), and the argument list is different, so they must be overloaded.

The constructor method overloads sample code is as follows:

//Person.java文件package com.a51work6;import java.util.Date;public class Person {// 名字private String name;// 年龄private int age;// 出生日期private Date birthDate;public Person(String n, int a, Date d) { ①name = n;age = a;birthDate = d;}public Person(String n, int a) { ②name = n;age = a;}public Person(String n, Date d) { ③name = n;age = 30;birthDate = d;}public Person(String n) { ④name = n;age = 30;}public String getInfo() {StringBuilder sb = new StringBuilder();sb.append("名字: ").append(name).append('\n');sb.append("年龄: ").append(age).append('\n');sb.append("出生日期: ").append(birthDate).append('\n');return sb.toString();}}

The above Code person class Code provides 4 overloaded construction methods, if you have accurate name, age, and date of birth information, you can use the Code section ① to create a person object, if only the name and age information can choose the code of ② line construction method to create a person object If only the name and date of birth information can be used to create a person object using the construction method of line ③, and if only the name information, you can use the construction method of line ④ to create the person object.

Construction method Encapsulation {#-2}

Construction methods can also be encapsulated, with access levels similar to normal methods, and the access level of the construction method is referenced in table 11-1. The sample code is as follows:

//Person.java文件package com.a51work6;import java.util.Date;public class Person {// 名字private String name;// 年龄private int age;// 出生日期private Date birthDate;// 公有级别限制public Person(String n, int a, Date d) { ①name = n;age = a;birthDate = d;}// 默认级别限制Person(String n, int a) { ②name = n;age = a;}// 保护级别限制protected Person(String n, Date d) { ③name = n;age = 30;birthDate = d;}// 私有级别限制private Person(String n) { ④name = n;age = 30;}...}

The preceding code, line ①, is a construction method that declares the public level. The code ② line is declared as the default level, and the default level can only be accessed in the same package. The code ③ line is a construction method of the protection level, which is the same as the default level in the same package and can be inherited by the quilt class in different packages. The code ④ line is a private-level construction method that can only be used in the current class, is not allowed to be accessed outside, and the private construction method may be applied to designs such as the singleton design pattern ^10.

The This keyword {#this}

The This keyword is used in the previous section, which points to the object itself and a class can obtain an object variable representing itself through this. This is used in three of the following cases:

    • Invokes an instance variable.
    • Invokes an instance method.
    • Call other constructor methods.

Sample code to use this variable:

 //person.java file package Com.a51work6;import Java.util.date;public class Person {// Name Private String name;//age private int age;//Birth date Private date birthdate;//Three parameters construction method public person (String name, int ages, Da Te d) {①this.name = Name;②this.age = Age;③birthdate = D; System.out.println (This.tostring ()); ④}public person (string name, Int. age) {//Call three parameter construction method this (name, age, null); ⑤}public person (string name, Date D) {//calls three parameters Construction method This (name, a, d); ⑥}public person (string name) {///SYSTEM.OUT.PRINTLN (this.tostring ());//Call person (string name, Date D) constructs the method this (name, NULL); ⑦} @Overridepublic String toString () {return " Person [name=" + name⑧+ ", age=" + age⑨+ ", birthdate=" + birthDate + & quot;] ";}}  

This keyword is used more than once in the above code and is analyzed in detail below. The Code section ① declares three parameter construction methods, where the parameter name and age conflict with the instance variable name and age, the parameter is a local variable scoped to the entire method, in order to prevent the local variable from naming the member variable, you can use this to call a local variable, see Code line ② and line ③. Note that the name and age variables of line ⑧ and line ⑨ do not conflict, so you can not use this call.

This can also call the method of this object, see the This.tostring () statement in line ④ of code, this example can be omitted.

When more than one constructor method is overloaded, a constructor method can call other construction methods, which can reduce the amount of code, ⑤ line This (name, age, NULL) using this to call other constructor methods. Similar calls are also available for this (name, ⑥, D) and ⑦ line of this (name, null) line of code.

Note When you use this to call other construction methods, the This statement must be the first statement of the constructed method. For example, an error occurs when the ToString () method is called before the ⑦ line of code.

Object Destruction

Objects should be destroyed when they are no longer in use. The C + + language object is manually released through the DELETE statement, and the Java language object is collected and then freed by the garbage collector (garbage Collection), and the programmer frees the details without a relationship. Automatic memory management is the trend of modern computer language, such as: C # language garbage collection, objective-c and Swift language arc (memory automatic reference count management).

The garbage collector (garbage Collection) works by saying that when a reference to an object does not exist and that the object is no longer needed, the garbage collector automatically scans the object's dynamic memory area, collecting the unreferenced objects as garbage and releasing them.

Summary of this chapter

By learning about this chapter, you can learn how to create Java objects and understand the role of construction methods. In addition, the use of this key is also described.

Companion video

Http://edu.51cto.com/topic/1246.html

Supporting source code

Http://www.zhijieketang.com/group/5

"Java from small white to Daniel" in the 11th chapter of the object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.