Java BASICS (6) -- classes and objects, java beginners objects

Source: Internet
Author: User

Java BASICS (6) -- classes and objects, java beginners objects

I finally wrote the last knowledge point in the entry article. Classes and objects are two frequently-mentioned words in Java. classes can actually be seen as objects and define the functions of objects. Java is an object-oriented language, so mastering classes and objects is the basis for learning the Java language.

The concepts of classes and objects are not described here. This essay mainly begins with the code, before learning this article, we recommend that you first understand the concepts of classes and objects, the concepts of instances, and the characteristics of object-oriented programs, that is, encapsulation, inheritance, and polymorphism.

I. Category

A class is a carrier that encapsulates the attributes and behaviors of an object. In Java, the attributes of an object exist in the form of member variables, and the object methods exist in the form of member methods.

1. Class Constructor

  The constructor is a method with the same name as a class.The object is created by constructor. constructor methods are divided into constructor methods and constructor methods. The difference is that there are no parameters. Is it a bit numb to say so many concepts? Let's look at the example below.

1 public class Example {2 3 public Example () {// defines the construction method without parameters 4 System. out. println ("construction method without Parameters"); 5} 6 7 public Example (String name) {// define construction method with parameters 8 System. out. println ("Construction Method with Parameters"); 9} 10 11}

When defining a constructor, there is no return value for the constructor, And the constructor does not require the void keyword to be modified. "Public" is the modifier of the constructor, and "Example" is the name of the constructor.

Assign values to member variables in the constructor. In this way, when an object of this class is instantiated, the corresponding member variables will also be initialized.

2. Main method of the class

We have already seen the main method many times. The Java compiler uses the main method to execute the program, which is the entry point of the class. The syntax format is as follows:

public static void main(String[] args) {    // ...}

"Static" means that the main method is static. If other methods are called in it, the method must also be static. "void" means that the main method has no return value; "String [] args" indicates that the main method's parameters are arrays, and args [0] ~ Args [n] indicates the first to nth parameters of the program. You can use args. length to obtain the number of parameters.

3. member variables

The property of an object is called a member variable or an attribute. The following is an example of a student ID card:

1 public class Student {2 private int id; // defines an int-type member variable, Student id 3 private String name; // defines a String-type member variable, name 4 5 public Student () {// defines the construction method without parameters 6 7} 8 public Student (int id, String name) {// defines the construction method with parameters 9 this. id = id; 10 this. name = name; 11} 12 13 public void setName (String name) {// defines a setName () method for importing the Student name 14 this. name = name; // assign the parameter value to the member variable 15} 16 public String getName () {// define a getName () method for obtaining the Student name 17 return this. name; 18} 19 20 public Student getStudent () {// return Student class reference 21 return this; 22} 23}

This is a comprehensive example. In Java, the class keyword is used to define the class. Student is the class name. Three member variables are defined in the Student class, they are student IDs and names respectively. You can set or do not set the initial values. If you do not set the initial values, there will be default values. The private keyword is used to define a private member. public, protected, and private will be introduced later. The following two constructor methods have already been mentioned. this keyword is used to reference the member variables and methods of an object, which will be described later. Generally, in such a class, each variable will have the set and get methods. The set method has a method with parameters and has no return value. The get method has a return value method for obtaining. Finally, there is a getStudent () method, which belongs to the Student class and is used to return the reference of the Student class, which is implemented using the this keyword.

4. Member Methods

The behavior of the class corresponding to the member method is the getName () and setName () methods in the above instance. They are respectively used to obtain the Student name and set the Student name. The syntax format is as follows:

Permission modifier return value type method name (parameter type parameter name) {//... return value ;}

If no return value is returned, the return value type is expressed by the void keyword, as shown in the preceding setName () method. If a return value exists, the return value type must be the same as the return value type of the method.

5. Local Variables

If a variable is defined in the member method, this variable is not called a local variable. For example, define a local variable id in the getName () method of the Student class as follows:

Public String getName () {int id = 0; // defines a local variable return id + this. name ;}

Local variables are created during method execution and destroyed at the end of method execution. values must be assigned or initialized during use. SoThe effective range of a local variable starts from the declaration of the variable to the end of the variable..

If a method contains a local variable with the same name as a member variable, access to this variable in the method is made using a local variable. For example, id = 0 in the above method, instead of the value of the member variable id in the Student class.

6. Static variables, constants, and methods

Static variables, constants, and methods are called static variables, constants, and methods. Static members belong to the class. Different from individual objects, you can use the class name and ". "operator call. This example also appears in the previous section. The syntax format is: Class Name. static class members.

1 public class StaticTest {2 final static double PI = 3.1415926; // define a static constant 3 static int id in the class; // define the static variable 4 5 public static void demo01 () {6 System. out. println ("test"); 7} 8 public static void main (String [] args) {9 System. out. println (StaticTest. PI); // call the static constant 10 System. out. println (StaticTest. id); // call static variable 11 StaticTest. demo01 (); // call static method 12} 13 14}
7. Permission Modifier

The permission modifiers in Java mainly include private, public, and protected, which control access to member variables of classes and member methods. The differences are as follows:

Access location Class Modifier
Private Protected Public
This class Visible Visible Visible
Other classes or subclasses of the same package Invisible Visible Visible
Classes or subclasses of other packages Invisible Invisible Visible

If the access permission of a class is invisible, this class will hide all the data in it to avoid direct access to it. When declaring a class, you do not use the public, protected, or private modifier to set the class permission, the class is preset as the package access range, that is, only the classes in the same package can call the member variables or member methods of this class.

Pay special attention to the following situations: Create an AnyClass class under the com. adamjwh package in the project. This class uses the default permission:

package com.adamjwh;class AnyClass {    public void doString() {        // ...    }}

In this case, even if the doString () method in the AnyClass class is set to public access, its access permission is the same as that of the AnyClass class. Because Java requires that the permission setting of a class will constrain the permission setting on the members of the class, the above Code is equivalent to the following code:

package com.adamjwh;class AnyClass {    void doString() {        // ...    }}
8. this keyword

In Java, the this keyword is implicitly used to reference the member variables and methods of an object, as shown in the preceding example in "member variables:

Public void setName (String name) {// defines a setName () method for importing the Student name this. name = name; // assigns the parameter value to the member variable}

In the setName () method, this. name specifies the name variable in the Student class, while the second name in the "this. name = name" statement specifies the parameter name. In essence, the setName () method is used to assign the value of the parameter name to the member variable name.

In addition to calling member variables or member methods, this can also be used as the return value of methods. As shown in the previous example in "member variables:

Public Student getStudent () {// return the Student class reference return this ;}

In the getStudent () method, the return value of the method is the Student class, so the return this form is used in the method body to return the objects of the Student class.

Ii. Objects

Java is an object-oriented programming language. objects are abstracted by classes. All problems are handled by objects. Objects can operate the basic attributes and methods of classes to solve the corresponding problems.

1. Create an object

In Java, you can use the new operator to call the constructor to create an object. The syntax format is as follows:

Test test = new Test();Test test = new Test("a");

When the test object is created, the test object is a reference to the object. This reference allocates storage space for the object in memory. You can initialize the member variable in the constructor. when creating the object, automatically call the constructor.

Objects and instances in Java can be used in fact. The following describes an instance for creating objects.

Public class CreateObject {public CreateObject () {// constructor System. out. println ("test");} public static void main (String [] args) {new CreateObject (); // create an object

Create an object using the new operator in the main method of the above instance. When creating an object, the code in the constructor is automatically called.

2. properties and behavior of the Access Object

After you create an object using the new operator, you can use "object. class member" to obtain the attributes and behaviors of the object. If you don't have much to say, go directly to the code.

1 public class ObjectTest {2 3 int I = 2018; // member variable 4 public void call () {// member Method 5 for (I = 0; I <3; I ++) {6 System. out. print (I + ""); 7 if (I = 2) {8 System. out. println (); // newline 9} 10} 11} 12 13 public ObjectTest () {// constructor 14} 15 16 public static void main (String [] args) {17 ObjectTest o1 = new ObjectTest (); // create an object 18 ObjectTest o2 = new ObjectTest (); // create another object 19 o2. I = 60; // assign 20 21 System to the second class member variable. out. println ("the result of the First Instance Object calling variable I is:" + o1. I); 22 (); 23 System. out. println ("the result of the second instance object calling variable I is:" + o2. I); 24 (); 25} 26 27}

The running result is as follows:


Here we can see that although two objects call the same member variable, the results are different, because the value is assigned to 60 again before the value of this member variable is printed, however, when assigning values, the member variable called by the second object o2 is used. Therefore, when the first object o1 calls the member variable to print the value, it is still the initial value of the member variable. Therefore, the two objects are mutually independent.

If you want the member variables not to be changed by any of the objects, you can use the static keyword, or change the code of the third line to static int I = 2018;. The running result is as follows:


Here, because the code "o2. I = 60;" in line 19th changes the value of the static member variable, the value of the member variable called by the object o1 is also changed to 60; after "o1. I" is executed, call the call () method again to re-assign the value of I to 0, print it cyclically, and finally I to 3. Exit the loop, therefore, the value of the member variable called by the object o2 is changed to 3.

3. Object Reference, comparison, and destruction

The syntax format of Object Reference is: Class Name Reference object name. For example, a reference to a Student class can be: Student student;. The syntax associated with the reference object is: student student = new Student ();.

The comparison of objects includes the "=" operator and the equals () method. The difference has been described in the previous article. The equals () method is a method in the String class. It is used to compare whether the content referenced by two objects is equal, and the "=" operator compares whether the addresses referenced by two objects are equal.

Object destruction uses the garbage collection mechanism in Java. users do not have to worry about memory usage of discarded objects. The Garbage Collector will recycle useless memory-occupied resources. Java virtual machines are considered as spam objects in the following two situations:

(1) The object reference exceeds the scope of its function;

(2) assign an object null;

Although the garbage collection mechanism has been improved, the garbage collector can only recycle objects created by the new operator. Therefore, Java provides a finalize () method. If you define the finalize () method in the class, this method is called first during garbage collection, in addition, the memory occupied by objects can be truly reclaimed only when the next garbage collection action occurs. Because garbage collection is not controlled by humans, Java also provides the System. gc () method to force the Garbage Collector to be started. The function is to notify the Garbage Collector to clean up.


This is all the content of the Java getting started article. to be proficient in using the Java language, there is still a lot of knowledge waiting for us to explore. It is no problem to master the knowledge of getting started articles to cope with the exams of the school, if you want to develop some games or projects, you need to learn more about the Java language. The next article is the advanced article on Java, the main content includes interfaces, inheritance, polymorphism, exception handling, input and output, Java Collection classes, and Swing programming (graphical interface.

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: 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.