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 knowledge points about classes and objects in Java?

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

Share

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

This article introduces what are the relevant knowledge points of classes and objects in Java, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Process-oriented and object-oriented understanding

C language is process-oriented, pays attention to the process, analyzes the steps of solving the problem, and solves the problem step by step through function call.

JAVA is based on object-oriented and focuses on objects. It divides a thing into different objects and relies on the interaction between objects.

Process-oriented focuses on the process, which refers to the behavior involved in the whole process.

Object-oriented focuses on the object, that is, the subject involved in the process. Is to connect the functions one by one through logic.

Process-oriented: 1. Open the refrigerator 2. Put things in 3. Refrigerator closed object-oriented: open the refrigerator, store, close the refrigerator is the operation of the refrigerator, is the passive behavior of the refrigerator. The refrigerator is an object, so as long as you operate the function of the refrigerator, it should be defined in the refrigerator (that is, class).

Second, the understanding and understanding of class and object.

A class is a general term for a class of objects. An object is an example of this kind of materialization. A class can be compared to a template, which may contain many attributes or functions. What is instantiated according to the template is called an object. A template can instantiate multiple objects.

To declare a class is to create a new data type, while the class is a reference type in Java, and Java uses the keyword class to declare the class. The following is the definition of the declaration class:

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

Class is the keyword that defines the class, ClassName is the name of the class, and {} is the body of the class.

The elements in the class are called: member attributes. The functions in the class are called member methods.

Example: a class is declared here

Class Person {public int age;// member property instance variable public String name; public String sex; public void eat () {/ / member method System.out.println ("eat!");} public void sleep () {System.out.println ("sleep!");}} class Person {public int age;// member property instance variable public String name; public String sex Public void eat () {/ / member method System.out.println ("eat!");} public void sleep () {System.out.println ("sleep!");}} public class Main {public static void main (String [] args) {Person person = new Person (); / / instantiate object person.eat () through new / / member method calls need to call person.sleep () through the object's reference; / / generate object instantiation object Person person2 = new Person (); Person person3 = new Person ();}}

The output is as follows:

Eat!

sleep!

Note:

The new keyword creates an instance of an object.

Use. To access the properties and methods in the object.

You can create multiple instances of the same class.

III. Members of the class

Members of a class can contain the following: fields, methods, code blocks, inner classes, interfaces, and so on. The first three are highlighted here.

1. Field / attribute / member variable

Variables defined outside the method in the class are called "field" or "property" or "member variable" (all three names are fine, generally not strictly distinguished).

Class Person {public String name; / / Field public int age;} class Test {public static void main (String [] args) {Person person = new Person (); System.out.println (person.name); System.out.println (person.age);}} / / execute the result null0

Note:

Use. Access the fields of the object.

Access includes both reading and writing.

If the initial value is not explicitly set for the field of an object, it will be set to a default initial value.

Default value rule

For various number types, the default value is 0. 0.

For the boolean type, the default value is false.

For reference types (String, Array, and custom classes), the default value is null

two。 Basic understanding of null

Null is a null reference in Java, which means that no object is referenced. Similar to the null pointer in C language. If carry on to null. The operation throws an exception.

Class Person {public String name; public int age;} class Test {public static void main (String [] args) {Person person = new Person (); System.out.println (person.name.length ()); / / get string length}} / / execution result Exception in thread "main" java.lang.NullPointerException / / null pointer exception at Test.main (Test.java:9)

Field initialization in place:

Although we do not want the properties to be initialized in place because of the default values, we will try not to initialize the fields in place, otherwise the program will be very rigid.

Class Person {public String name = "Zhang San"; public int age = 18;} class Test {public static void main (String [] args) {Person person = new Person (); System.out.println (person.name); System.out.println (person.age);}} / / execution result Zhang San 18

What should be noted in the quote:

1. The following code refers to the person2 reference to the object that the person reference points to.

Public static void main (String [] args) {Person person = new Person (); Person person2 = person;}

two。 A reference cannot point to more than one object, and even after pointing to the object multiple times, it can only point to the last object.

3. We know that local variables open up memory on the stack, and it stores addresses, also known as references. So must the reference be on the stack? The answer is no. Look at the following code:

Class Person {public String name; public int age;} public class TestDemo {Person person = new Person (); public static void main (String [] args) {TestDemo testDemo = new TestDemo ();}}

Memory layout:

3. Method (method)

The specific behavior used to describe an object is called a method.

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

Such a show method is associated with an person instance, and if other instances are created and the properties in the class are reassigned, the behavior of the show will change.

Person person2 = new Person (); person2.name = "Li Si"; person2.age = 20 4.static person2.show (); / / execution result my name is Li Si, 20 years old this year

What the static keyword does:

Decorate the property (memory is opened in the method area)

Decorate the method (open memory in the stack only when the method is called)

Code block (introduced in this courseware)

Modifier class (which will be discussed later in the inner class)

1) decorated attributes: Java static properties are class-related and have nothing to do with specific instances. In other words, different instances of the same class share the same static property.

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

Output result:

one

one

=

one

two

If you need to call an attribute in a class that has static, you only need the class name. Property can be called, but not the object name. Property, otherwise the compiler will report a warning.

Open up in the memory method area of a member variable modified by static because it does not belong to an object and therefore does not open memory on the heap; open memory in the method area and open it only once.

The following figure shows the relationship between objects, classes, and properties (instance member variables, static member variables).

2) Modification method

If you apply the static keyword to any method, this method is called a static method.

Static methods belong to the class, not to the object of the class.

You can call static methods directly without creating an instance of the class.

Static methods can access static data members and can change the values of static data members.

Class TestDemo {public int a; public static int count; public static void change () {count = 100; / / a = 10; error cannot access non-static data members}} public class Main {public static void main (String [] args) {TestDemo.change (); / / you can call System.out.println (TestDemo.count) without creating an instance object;}}

Output result:

one hundred

Note: static methods have nothing to do with instances, but are related to classes. So this leads to two situations:

Static methods cannot directly use non-static data members or call non-static methods (both non-static data members and methods are instance-related).

The keywords this and super cannot be used in a static context (this is a reference to the current instance, super is a reference to the parent instance of the current instance, and is also related to the current instance)

Because the main method is a static method, you can only instantiate other classes before calling instance member variables or instance member methods in other classes. of course, the main method can also directly use the class name to call static member variables or static methods in other classes.

Static variables belong to the class, so static methods modified by static (including normal methods and static methods) cannot be defined in methods, but can be initialized or used.

Static methods can be called in ordinary methods, while ordinary methods can not be called in static methods, but other static methods can be called.

Observe the following code and understand its memory layout:

Class Person {public int age;// instance variables are stored in the object public String name;// instance variables public String sex;// instance variables public static int count;// class variables, also known as static variables, have been generated at compile time, belong to the class itself, and have only one copy. Stored in the method area public final int SIZE = 10 final / modified by the constant is also an object. Modified by final, the subsequent constant that cannot be changed is public static final int COUNT = 99 int / static constant, which belongs to the class itself, only one copy is modified by final, and the subsequent immutable / instance member function public void eat () {int a = 10 politics / local variable System.out.println ("eat ()!") } / / instance member function public void sleep () {System.out.println ("sleep ()!");} / / static member function public static void staticTest () {/ / cannot access non-static member / / sex = "man"; error System.out.println ("StaticTest ()") }} public class Main {public static void main (String [] args) {/ / generate object instantiation object Person person = new Person (); / / person is the reference System.out.println (person.age) of the object; / / default is 0 System.out.println (person.name); / / default is null / / System.out.println (person.count) / / there will be warnings! / / correct access methods: System.out.println (Person.count); System.out.println (Person.COUNT); Person.staticTest (); / / Summary: all methods or properties modified by static do not depend on the object. Person.eat (); person.sleep ();}}

The output is as follows:

0

Null

0

ninety-nine

StaticTest ()

Eat ()!

Sleep ()!

Memory layout of data properties:

IV. Encapsulation

What is encapsulation? To put it simply, when we write code, we often involve two kinds of roles: the implementer of the class and the caller of the class, and encapsulation enables the caller of the class to have nothing to do with how the implementer of the class implements the class. as long as you know what methods are called directly in the class. The learning and use costs of class users are reduced, thus the complexity is reduced.

1. Private implementation encapsulation

The two keywords private/ public are access modifier qualifiers.

Member variables or member methods modified by public can be directly used by the caller of the class to use the member variable or method modified by private, but not by the caller of the class.

Use public directly:

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

Such code causes the consumer of the class (the code of the main method) to understand the internal implementation of the Person class in order to use the class, which is expensive to learn.

Once the implementer of the class modifies the code (for example, changing name to myName), then the users of the class need to modify their own code on a large scale, which is expensive to maintain.

Use private:

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

At this point, the field has been decorated with private, and the caller of the class (in the main method) cannot use it directly. But need to rely on the show method. At this point, the consumer of the class does not need to know the implementation details of the Person class.

At the same time, if the implementer of the class changes the name of the field, the caller of the class does not need to make any changes (the caller of the class cannot access fields such as name and age at all).

Private can not only modify fields, but also modify methods.

Normally, we set the field to the private property, but whether the method needs to be set to public depends on the situation. In general, we want a class to provide only the "necessary" public methods, rather than setting all methods to public.

2.getter and setter methods

A field decorated by private does not mean that the field cannot be used outside the class. So how do you get the fields decorated by private outside the class? Here jdk provides us with getter and setter methods.

Code example:

Class Person {private String name;// instance member variable private int age; public void setName (String name) {/ / name = name;// cannot be written in this way, otherwise name is still 0, local variable precedence this.name = name;//this reference, indicating the name} public String getName () {return name;} public void show () {System.out.println ("name:" + name+ "age:" + age) of the object calling the method. }} public static void main (String [] args) {Person person = new Person (); person.setName ("caocao"); String name = person.getName (); System.out.println (name); person.show ();} / / run result caocao name: caocao age: 0

Note:

GetName is the getter method, which means to get the value of this member.

SetName is the setter method, which means to set the value of this member

When the parameter name of the set method is the same as the name of the member property in the class, if you do not use this, it is equivalent to a self-assigned value. This represents a reference to the current instance

Not all fields have to provide setter / getter methods, but decide which method to provide according to the actual situation.

You can use alt + insert (or alt + F 12) to quickly generate setter / getter methods in IDEA. In VSCode, you can use the right mouse button menu-> source code operation to automatically generate setter / getter methods

Fifth, the construction method 1. The basic syntax and use of construction methods

The constructor is a special method that is automatically called when a new object is instantiated with the keyword new to complete the initialization operation.

New execution process:

Allocate memory space for objects

Call the constructor of the object

Grammar rules:

Method name must be the same as class name.

The constructor does not return a value type declaration.

There must be at least one constructor in every class (if not clearly defined, the system automatically generates a no-parameter constructor)

Note:

If no constructor is provided in the class, the compiler generates a constructor without arguments by default.

If a constructor is defined in the class, the default no-parameter construct will no longer be generated, and if you need to call the no-parameter constructor, you need to write one manually.

The constructor supports overloading, and the rules are consistent with the overloading of common methods. (the return value is not required, the method name is the same, and different parameters may include different number of parameters or different parameter types)

Code example:

Class Person {private String name;// instance member variable private int age; private String sex; / / default constructor constructor object public Person () {this.name = "caocao"; this.age = 10; this.sex = "male";} / / Constructor public Person (String name,int age,String sex) with three parameters {this.name = name; this.age = age; this.sex = sex } public void show () {System.out.println ("name:" + name+ "age:" + age+ "sex:" + sex);}} public class Main {public static void main (String [] args) {Person p1 = new Person (); / / call constructor without arguments if the program does not provide the constructor p1.show (); Person p2 = new Person ("zhangfei", 80, "male") / / call the constructor p2.show () with three parameters;}} / / execute the result name: caocao age: 10 sex: male name: zhangfei age: 80 sex: male 2.this keyword

This represents the current object reference (note that it is not the current object), and you can use this to access the fields and methods of the object. This represents the current object reference because the appropriate constructor is called during the creation of the object, and the this keyword can be used inside the constructor, and the this keyword is used during the creation of the object (the object has not yet been created), proving that this points to the reference of the current object.

Class Person {private String name;// instance member variable private int age; private String sex; / / the default constructor constructor object public Person () {/ / this calls the constructor this ("bit", 12, "man"); / / must be placed on the first line to display} / / the relationship between the two constructors is overloaded. Public Person (String name,int age,String sex) {this.name = name; this.age = age; this.sex = sex;} public void show () {System.out.println ("name:" + name+ "age:" + age+ "sex:" + sex);} public class Main {public static void main (String [] args) {Person person = new Person (); / / call the constructor person.show () without arguments }} / / execution result name: bit age: 12 sex: man

This can refer to properties in the reference of the current object or can be used inside the constructor (only within the constructor if other constructors are called).

Code example:

Class Person {private String name; private int age; public Person () {this ("zjr", 18);} public Person (String name, int age) {System.out.println ("name:" + name+ "age:" + age);}} public class TestDemo {public static void main (String [] args) {Person person = new Person ();}}

Running result:

Conclusion:

If you use the this keyword to call another constructor on the second line, you will get an error; and the constructor can only be called once. To get used to using the this keyword, the this keyword effectively avoids errors when assigning the same variable names on both sides of an object's properties.

VI. Code blocks in Java

Fields can be initialized in the following ways:

In-place initialization

Class using the constructor method

Initialization using a code block

The first two initialization methods have been introduced, so how to initialize attributes simply with code blocks?

1. Recognize the code block

Use a piece of code defined by {}.

According to the location of the code block definition and keywords, it can be divided into the following four categories:

Normal code block (for understanding only)

Tectonic block

Static block

Synchronous code block (we'll talk about it later in the multithreading section)

two。 Ordinary code block

Normal code block: a code block defined in a method.

Public class Main {public static void main (String [] args) {{/ / directly use {} definition, common method block int x = 10; System.out.println ("x1 =" + x);} int x = 100; System.out.println ("x2 =" + x);}} / / execution result x1 = 10 x2 = 1003. Construct code block

Building block: a block of code defined in a class (without modifiers). Also known as: example code block. The construction code block is typically used to initialize instance member variables.

Code example:

Class Person {private String name;// instance member variable private int age; private String sex; public Person () {System.out.println ("I am Person init ()!");} / / instance code block {this.name = "bit"; this.age = 12; this.sex = "man"; System.out.println ("I am instance init ()!") } public void show () {System.out.println ("name:" + name+ "age:" + age+ "sex:" + sex);}} public class Main {public static void main (String [] args) {Person p1 = new Person (); p1.show ();}} / / run the result I am instance init ()! I am Person init ()! Name: bit age: 12 sex: man

Note: instance code blocks take precedence over constructor execution.

4. Static code block

Use the code block defined by static. It is generally used to initialize static member properties.

Class Person {private String name;// instance member variable private int age; private String sex; private static int count = 0 bit / static member variable shared by class data method area public Person () {System.out.println ("I am Person init ()!");} / / instance code block {this.name = "bit"; this.age = 12; this.sex = "man"; System.out.println ("I am instance init ()!") } / / static code block static {count = 10 sex / can only access static data member System.out.println ("I am static init ()!");} public void show () {System.out.println ("name:" + name+ "age:" + age+ "sex:" + sex);}} public class Main {public static void main (String [] args) {Person p1 = new Person (); Person p2 = new Person () / / will static code blocks still be executed? }}

Note:

No matter how many objects are generated, the static code block is executed only once and first.

After the static code block is executed, the instance code block (constructor block) executes, followed by the constructor execution.

Only static code blocks can be executed without instantiating objects. As long as a variable or method in the class is called (static), it can be executed. The execution of the static code block is performed during the loading process of the class, so it is executed only once.

The use of base variables for static code blocks is similar to the static method, and this and definition variables modified by static cannot appear, independent of the object.

Static variables can be used in static code blocks, but the order in which statically decorated code blocks and variables are executed is not the same, and it is determined according to the order in which the code is executed (provided that initial values have been given at initialization. Otherwise, it still follows the order in which static code blocks are executed first. For example:

Class Person {public String name; public int age; public static int count= 10; static {count=99; System.out.println (static);} {System.out.println (instance);}} public class TestDemo {public static void main (String [] args) {Person person = new Person (); System.out.println (Person.count);}}

Running result:

Exchange execution order:

Class Person {public String name; public int age; static {count=99; System.out.println ("static");} public static int count= 10; {System.out.println ("instance");}} public class TestDemo {public static void main (String [] args) {Person person = new Person () System.out.println (Person.count);}}

Therefore, if the static variable is not assigned an initial value, the result is the value assigned within the static code block; if the static variable is assigned an initial value, the last value of the amount is determined according to the execution order, except that the variable assignment statement execution order is different. all statements in the static code block are executed first.

The focus in the code block is to understand the running order of the instance code block, the static code block, and the constructor. Summary: first run the static code block, then run the example code block (construction code block), and finally run the construction method. Within a static code block is run only once.

7. ToString method 1. Override the toString method of println

We just noticed that when we printed the properties of the object, we implemented the show function ourselves. But in Java it provides a way for us to print properties. It's called toString method.

Code example:

Class Person {private String name; private int age; public Person (String name,int age) {this.age = age; this.name = name;} public void show () {System.out.println ("name:" + name+ "" + "age:" + age);} / / rewrite Object's toString method @ Override public String toString () {return "Person {" + "name='" + name+'\'+ ", age=" + age +'}' }} public class Main {public static void main (String [] args) {Person person = new Person ("caocao", 19); person.show (); System.out.println (person);}} / / execution result name:caocao age:19 Person {name='caocao', age=19}

Note:

The toString method is called automatically during println

The operation of converting an object to a string is called serialization.

ToString is the method provided by the Object class. The Person class we created inherits from the Object class by default. We can override the toString method to implement our own version of the conversion string method. We will focus on the concepts of inheritance and rewriting later.

@ Override is called a "comment" in Java, and @ Override here means that the toString method implemented below is a method that overrides the parent class, which will be described in more detail in the lessons that follow.

IDEA quickly generates Object's toString method Shortcut key: alt+f12 (insert)

If we want to observe the toString method in println, we can press and hold the ctrl key and click the mouse to the location in the println. Click into println and you will see as shown in the figure:

Then press the ctrl key to place the mouse on the red box and click, as shown in the figure:

Finally, you will enter the method in the red box, as shown in the figure:

So we can confirm that the toString method in println is printed after processing according to the hash value. So if we rewrite its toString method to print the properties in our class, we can directly System.out.println (person); (the code is shown above), and if we don't override the toString method in println, then use System.out.println (person); the printed result is: class name + @ + hashed address.

two。 Anonymous object

Anonymity only means an object without a name.

An object without a reference is called an anonymous object

Anonymous objects can only be used when creating objects

If an object is only used once and does not need to be used later, consider using anonymous objects

Class Person {private String name; private int age; public Person (String name,int age) {this.age = age; this.name = name;} public void show () {System.out.println ("name:" + name+ "+" age: "+ age);}} public class Main {public static void main (String [] args) {new Person (" caocao ", 19). Show () / / call method via anonymous object}} / / execute the resulting name:caocao age:19

Important: notice how anonymous objects call methods in the class.

Exchange the values of two numbers (argument exchange)

Code:

Class Test {private int num; public int getNum () {return num;} public void setNum (int num) {this.num = num;}} public class TestDemo2 {public static void Swap (Test test1,Test test2) {int tmp = test1.getNum (); test1.setNum (test2.getNum ()); test2.setNum (tmp) } public static void main (String [] args) {Test test1 = new Test (); Test test2 = new Test (); test1.setNum (10); test2.setNum (20); System.out.println (test1.getNum ()); System.out.println (test2.getNum ()); Swap (test1,test2); System.out.println (test1.getNum ()) System.out.println (test2.getNum ());}}

Running result:

On the Java classes and objects of the relevant knowledge points shared here, I hope that 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: 0

*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