Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the classes and objects and code blocks in Java?

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail about the classes and objects and code blocks in Java. The content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

1. A preliminary understanding of classes and objects

Java is an object-oriented language, the so-called object-oriented is different from process-oriented, object-oriented is only the interaction between objects to complete the task, but process-oriented, we need to do every step in detail. For example, take laundry as an example, if it is a process-oriented attack on clothes, then we first need clothes, then put them in a basin, then add water, put laundry powder, and finally rub them. But if you are object-oriented, the first step is to find objects, such as clothes, washing powder, washing machine and water, and put them all in the washing machine. This is the interaction between objects.

The class in java is the synthesis of objects, for example, the object is a house, then the class is the design drawing, and each object is a concrete individual of the class.

two。 Instantiation of class

In short, from the above analysis, it is not difficult to come to the conclusion that the general name of similar objects, objects are concrete instances of this class, a class can produce countless objects. So what I'm writing code is to instantiate the class, that is, to extract a specific object (equivalent to a physical object) from the class (that is, the template).

Basic syntax:

/ / create class class {field;// attribute method;// member method} / / instantiate an object = new ()

Class is the keyword that defines the class, ClassName is the name of the class, and {} is the body of the class. (note: java's class is named using a large hump, and the naming rules for java components are attached here.)

Elements in a class but outside member methods can be called: fields / attributes / member variables (all three).

The functions in the class are called member methods.

The instantiation method of the class

Class Person {public int age; / / field public String name; public String sex; public void eat () {/ / method system.out.println ("eat");} public void sleep () {system.out.println ("sleep");}} 3. Members of the class

Field (attribute / member variable) class Person {/ / create a class public String name; / / member variable public int age; public void eat () {int a = 0politics / local variable System.out.println ("eat");} class Test {/ / create a class public static void main (String [] args) {/ / main function Person person = new person () / / instantiate a specific object System.out.println (person.name); / / print out System.out.println (person.age); person.eat ();}} / / execute the result null0

Note:

As shown in lines 13 and 14 above, you can use periods to access the fields in the instantiated object.

If the member variable does not have an initial value assigned

Then the reference type defaults to NULL, and the basic type defaults to 0.

If it is of boolean type, the default is false

If it is of char type, the default is "\ u0000" (which is actually empty)

Access includes both reading and writing, reading, that is, you can use a period to find the member variable, write, that is, you can assign a value to it (I think this is nonsense, but when the textbook sees it, it is bb).

In addition, if the reference is set to null, then a null pointer exception will occur and the code will report an error if it is referenced later with a period. (as shown in the following figure)

Person is a reference variable when line 11 is instantiated, which opens up a space in the computer's stack space for person and a space on the heap to store objects, and person refers to the objects above the stack space.

Similarly, the an in the fifth line is a local variable because it is in the function, so it is stored in the stack space.

Method

To put it bluntly, the method in java is a function, which is essentially a kind of behavior made by an object.

Class Person {public int age = 18; public String name = "Zhang San"; public void show () {System.out.println ("my name is + name, this year + age + year");}} class test {public static void main (String [] args) {Person person = new Person (); person.show ();}}

As above, that is to say, Zhang San has an action to be performed called show.

But if you want to create another object and print it in show, you need person to refer to the relevant properties in the class with a period.

Person person2 = new Person (); person2.name = "Li Si"; person2.age = 20 personal.show ()

But it should be noted that the Person class at the top of the code here has already assigned initial values to member variables when instantiating, which is actually wrong, because as mentioned above, the class is actually the sum of all objects, and he cannot be specified in this way (to put it simply, it is impossible for everyone to be called Zhang San).

Note: in real development, it is impossible for us to write the show function every time we want to print, so there is a shortcut, that is the toString method, right mouse button click to find generate and then it will jump, and then you can find it.

In fact, the principle is that the println print alcohol source is actually called a class called object in the toString method, here our operation is to rewrite this method, so that after the change, the following code can directly print the effect we want when it is printed with println.

For example, we changed the two red boxes in the above picture, then each time the print code outputs the effect we want. As shown in the following figure, the upper line shows the output of the show () function, while the following line shows the effect of rewriting the toString output

Static keyword

(static can modify fields, methods, code blocks, classes)

Things decorated by static do not need to instantiate the object, use the object to point xx to access, he can directly use the class name point xx to access.

Decorated field

Static member variables (or class variables) are placed independently in the method area, with only one copy, taking the following example as an example

Class TestDemo {public int a; public static int count;} public class Main {public static void main (String [] args) {TestDemo T1 = new TestDemo (); t1.aexamples; TestDemo.count++; System.out.println (t1.a); System.out.println (TestDemo.count); System.out.println ("="); T2 = new TestDemo (); t2.aexamples; TestDemo.count++; System.out.println (t2.a); System.out.println (TestDemo.count);}}

So the answer can be easily obtained from the way an and count are stored. Every time we instantiate a new object, a will be hit hard, so a will change, but there is only one copy of count, which is only stored in the method area, so when we re-new an object, count inherits the last value.

Modification method

The static method still opens up stack frames.

Static methods can be called directly, and there is no need to instantiate an object and then reference it as a normal method does. Therefore, the front of the main function is to add static, because static can allow the main function to be called directly through jvm, if not in this way, then you will have to new an object in the main function and let the object call the main function, but the current problem of the main function is that the new object must be in the main function, but the problem is that I can't even enter the main function now, so if you want to come in, you have to call the main function. To call, you must new the object in the main function. Obviously, this is a contradiction, and if you want to resolve this contradiction, you must add static to the main function.

Non-static methods can directly call static methods and non-static methods (that is, directly write the function name with parentheses on behalf of the call), but static methods can not be called directly, only static methods can be called directly, that is to say, if the main function wants to call other methods directly, it must let other functions add static, otherwise it will be troublesome to create objects again.

Modification code block (not to talk about) decoration class (not to talk about) 4. Encapsulation

In essence, private and public and these two keywords are used to encapsulate the function. Because the code we wrote before is directly modified with public, in this way, we have to specifically understand the situation in the class, which will make the code very troublesome to write, and if the creator of the class tampers with the names of the member variables in the original class, then the following code will also be changed, the safety factor is very low. So as long as we use private to encapsulate member variables, so that users can not be directly associated with member variables, but with functions in the class. If the member variable changes, the caller of the class does not need to make any changes.

All in all, when modified by private, its permissions are reduced and can only be used in the current class. Decorated by private can only be referenced by the class name.

Getter and setter

But when we modify our encapsulated fields, it is impossible to write getName () and setName () every time, so we can directly use the shortcut, right-click and select generate and then select the item we want to operate. (the following is an example), and this represents a reference to the object in which it currently resides.

5. Construction method

Constructor characteristics: there is no return value, the method name and class name are the same.

/ / the following is an example of a no-parameter constructor public Person () {}

The function of the constructor is to initialize the object, that is, to assign initial values to the member variables of the object before the object is created, because the creation of the object is divided into two steps, first allocating memory to the object, and then assigning the appropriate constructor to the object, that is, we can use this when we want to assign a value to the object in advance in the constructor. And because this is essentially the corresponding pointer assigned to the object by jvm after the object is created, it is also because this can be used in the constructor (the object has not been fully created at this time), which shows that this is actually a reference to the object, not the object itself.

When we instantiate an object, the compiler carries a no-argument constructor by default, but it does not automatically carry this method if there are already other constructors in the same class. The following three pieces of code are constructors, and their relationship is overloaded.

6. This usage

This. Member variable

This. Member method

This () uses this to call the constructor. There are several parameters in the constructor. This has several parameters in parentheses (note that the this call constructor must be placed on the first line)

In addition, the reason why we say that this is a reference object rather than an object is that the generation of an object is divided into two steps. The first step is to allocate memory for the object, and the second step is to call the appropriate constructor. After these two steps are completed, we can say that our object has been created. However, if our this is created in a constructor, we can clearly see that the this is not an object but a reference object. Because the this is still in the constructor code at this time, that is, the constructor object has not been created when this is used, so the this at this time is just a reference to the object.

Most of the time when this is used in a class, the object has not yet been created, and the this here is a reference to the object of the current class.

In addition, this cannot appear in static methods (static can only be referenced by class names).

A few considerations about references:

Do references only exist on the stack?

Answer: not necessarily, because when you create a member variable in a class that is an array, after your object is instantiated, the reference variable of the array will be placed on top of the object, but the reference variable of the array essentially refers to the elements in its own array.

Class Person {private String name; private int age; private int [] elem = new int [10];} / / the following is the schematic

Can a reference point to a reference?

Answer: no, references can only point to objects.

Person person = new person (); person1 = new person ()

From the above string of code, it is clear that the object pointed to by the reference person1 has been given a new object again and again, but even so, this does not mean that person1 points to multiple objects at the same time, and in the end, the valid object is only the fifth line, that is, person1 points to the object on the fifth line, and nothing else is useful.

A reference is assigned to null to indicate that it does not point to any object

Person = null;// example 7. Code block

Code blocks are divided into

Local code block (defined in the method) / / non-key

Example code block (construction code block)

{this.age = 19;} / / used to initialize member variables

Static code block

Static {} / / is used to request data for preparation

Synchronize code blocks (not to talk about it for the time being)

When the program is executed, the order of execution is as follows: the static code block is executed first (even at the end), then the instance code block is executed, and finally the constructor is executed. Also, in a class, static code is executed only once.

And when there is only the same type in a piece of code, it will be executed in the order from top to bottom. For example, if there are both static fields and static blocks of code in a class, who comes first and who executes first.

(construct code block)

{this.age = 19;} / / used to initialize member variables

Static code block

Static {} / / is used to prepare data in advance

Synchronize code blocks (not to talk about it for the time being)

When the program is executed, the order of execution is as follows: the static code block is executed first (even at the end), then the instance code block is executed, and finally the constructor is executed. Also, in a class, static code is executed only once.

And when there is only the same type in a piece of code, it will be executed in the order from top to bottom. For example, if there are both static fields and static blocks of code in a class, who comes first and who executes first.

On the Java classes and objects and code blocks are shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 236

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report