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

How to use the Class class and object class of Java

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "how to use the Class class and object class of Java". In the daily operation, I believe that many people have doubts about how to use the Class class and object class of Java. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about how to use the Class class and object class of Java. Next, please follow the editor to study!

A brief introduction to the Construction method in Java

A constructor is a special method of a class that initializes a new object of the class. Every class in Java has a default constructor that must have the same name as the class name and no return type. The default return type of the constructor is the object type itself, and the constructor cannot be modified by static, final, synchronized, abstract, and native.

Tip: constructors are used to initialize a new object, so there is no point in decorating with static; constructors cannot be inherited by subclasses, so decorating with final and abstract is pointless; multiple threads will not create the same object with the same memory address at the same time, so decorating with synchronized is not necessary.

The syntax format of the constructor is as follows:

Class class_name {public class_name () {} / / default no-parameter constructor public ciass_name ([paramList]) {} / / defines the constructor. / / Class body}

In a class, the same method as the class name is the constructor. Each class can have multiple constructors, but each of them is required to contain different method parameters.

Example 1 of construction method

There are two main construction methods: non-parametric construction method and parametric construction method. Examples are as follows:

Public class MyClass {private int m; / / define the private variable MyClass () {/ / define the no-parameter constructor this.m=m;;} MyCiass (int m) {/ / define the parameterized constructor this.m=m;}}

This example defines two construction methods, namely, the nonparametric construction method and the parametric construction method. Defining multiple methods of the same name with different parameters in a class is the overload of the method. Both constructors have the same name as the class name, which is MyClass. Different constructors can be called for initialization when the class is instantiated.

Note: the constructor of a class is not required to be defined. If no constructor is defined in the class, Java automatically generates a default constructor for the class. The default constructor does not contain any parameters, and the method body is empty. If one or more constructors are explicitly defined in the class, Java no longer provides default constructors.

Example 2

To create objects of a class with different initialization behaviors under different conditions, you need to create multiple constructors in a class. The following is an example to demonstrate the use of the construction method.

(1) first, define two constructors in the employee class Worker, as follows:

Public class Worker {public String name; / / name private int age; / / Age / / defines the constructor public Worker (String name) {this.name=name;} / / defines the constructor public Worker (String name,int age) {this.name=name; this.age=age with two parameters } public String toString () {return "Hello, everyone! I am a new employee. My name is "+ name+". I am "+ age+" this year. " ;}}

Two properties are defined in the Worker class, of which the name property is immutable. The constructors with one parameter and two parameters are defined and their properties are initialized. Finally, the toString () method of this class is defined and an introduction statement of the new employee is returned.

Tip: the Object class has a toString () method, which is a special method, and every class you create inherits it, which returns a string of type String. If the method is defined in a class, when the class object is called, the toString () method of the class object is automatically called to return a string, and then the returned string contents can be printed using "System.out.println".

(2) create the main () method in the TestWorker class as the entrance to the program, call different constructors in the main () method to instantiate the Worker object, and initialize the properties in the object as follows:

Public class TestWorker {public static void main (String [] args) {System.out.println ("- constructor with one parameter -"); / / call the constructor with one parameter, and the values of the sex and age properties in the Staff class remain unchanged Worker worker1=new Worker ("Zhang Qiang"); System.out.println (worker1) System.out.println ("- constructor with two parameters -"); / / call the constructor with two parameters, and the value of the sex property in the Staff class remains unchanged Worker worker2=new Worker ("Li Li", 25); System.out.println (worker2);}}

In the above code, two different Worker objects are created: an employee object named Zhang Qiang and an employee object named Li Li at the age of 25. For the first Worker object, Worker1, the age attribute value is not specified, so the program sets its value to the default value of 0. For the second Worker object, Worker2, the name property value and the age property value are assigned respectively, so the program reassigns the passed parameter value to the property value in the Worker class.

Run the TestWorker class and the output is as follows:

-Construction method with one parameter.-Hello, everyone! I am a new employee. My name is Zhang Qiang. I am 0 years old. -Construction method with two parameters.-Hello, everyone! I'm a new employee. My name is Li Li. I'm 25 years old.

By calling the constructor with parameters, the initialization of the object members is completed when the object is created, which simplifies the code of the object initialization.

Several construction methods in Java explain the common construction methods in detail

The method name is the same as the class name

No return type

A subclass cannot inherit the constructor of a parent class

Cannot be modified by static, final, abstract (those decorated with final and static cannot be inherited by subclasses, abstract modifies abstract classes, and abstract classes cannot be instantiated, that is, they cannot be new)

Can be modified by private, can be instantiated in this class, but not externally instantiated objects (note! )

Public class A {int iTuno; public A () {iTun2;} public A (int I) {this.i=i;}} default construction method

If there is no constructor, a default no-parameter constructor is automatically added at compile time

Implicit default construction method

Public A () {}

Default construction method displayed

Public A () {System.out.print ("default constructor displayed")} overloaded constructor

For example, the constructor in the original class has one parameter, but now the newly created object has three parameters, so it is necessary to overload the constructor.

When there are multiple constructors in a class, repetitive operations may occur, and other constructors can be called with this statements.

Public class A {private int age; private String name; public A (int age,String name) {this.age=age; this.name=name;} public A (int age) {this (age, "John Doe"); / / call A (int age,String name) constructor} public A () {this (1) / / call A (int age) constructor} public void setName (String name) {this.name=name;} public String getName () {return name;} public void setAge (int age) {this.age=age;} public int getAge () {return age;}} An a=new A (20, "Monday"); A b=new A (20); A c=new A (); String name= a.getName (); String name1 = b.getName (); int age= c.getAge () System.out.println (name); System.out.println (name1); System.out.println (age); Java subclass constructor calls parent constructor

First of all, the parent class constructor must not be inherited by the subclass.

The constructor of the subclass calls the constructor of the parent class. The point is that the constructor of the subclass calls the constructor of the parent class anyway.

The subclass constructor either calls the parent class no-parameter constructor, including when the parent class does not have a constructor. The system default to the no-parameter constructor), or call the parent class parameterized constructor. When the subclass constructor calls the parent class no-parameter constructor, it is generally not written by default. The word to be written is super (), and it should be placed in the first sentence of the constructor. When the subclass constructor wants to call the parent constructor with parameters, then the subclass constructor must call the parent constructor with super (parameter) and place it in the first sentence of the constructor.

When the constructor of a subclass is a no-parameter constructor, the parent-class no-parameter constructor must be called. Because the system will automatically find whether the parent class has a no-parameter constructor, if not, the system will report an error: the parent class does not define a no-parameter constructor.

When the subclass constructor is a parametric constructor, there are two situations.

The first: the subclass constructor does not write super, which means that you call the parent class parameterless constructor by default, which is the same as the subclass parameterless constructor.

The second kind: when the subclass constructor has super (parameters), the system will find whether the parent class has the same parameters (the number of parameters and the type order should be the same). If not, it will also report an error.

But here will encounter the same problem as the overloaded constructor this, the constructor of a parameter can call multiple parameter constructors, and it is possible to give a self-defined value to a parameter that does not exist.

An introduction to Code blocks in Java

Code blocks enclosed in {} in java are called code blocks, which can be divided into the following four categories:

one。 Brief introduction

1. Normal code block:

The method body of a method in a class

two。 Construct the code block:

The constructor block is called when the object is created, each time it is created, and takes precedence over the class constructor.

3. Static code block:

Code snippets wrapped in static {} are executed only once. Static code blocks take precedence over building blocks.

4. Synchronize code blocks:

Using the code block wrapped by synchronized () {}, in the multithreaded environment, the read and write operations of the shared data need to be mutually exclusive, otherwise it will lead to data inconsistency. The synchronization code block needs to be written in the method.

two。 Similarities and differences between static code block and construction code block

Similarities: all are executed after the JVM loads the class and before the constructor is executed, multiple can be defined in the class, and some static variables are generally assigned in the code block.

Difference: static code blocks are executed before non-static code blocks. Static code blocks are executed only once on the first new, and are not executed afterwards. Instead of static code blocks, they are executed once per new.

Java code blocks use partial code blocks

Location: local location (inside the method)

Function: limit the life cycle of variables, release as soon as possible, and save memory

Call: execute when the method it is in is called

Public class partial code block {@ Testpublic void test () {BB = new B (); b.go () }} class B {B () {} public void go () {/ / local code blocks in the method generally make an one-time call, releasing space immediately after the call, so as to avoid occupying stack space in the next call process / / because the stack space memory is limited, method calls may generate a lot of local variables, resulting in insufficient stack memory. / / this can be avoided by using partial code blocks. {int I = 1; ArrayList list = new ArrayList (); while (I < 1000) {list.add (I + +);} for (Integer j: list) {System.out.println (j);} System.out.println ("gogogo") } System.out.println ("hello");}} construct the code block

Location: the position of a member of a class, that is, a location other than a method in a class

Function: to extract the common parts of multiple construction methods and share construction blocks

Call: every time a constructor is called, it takes precedence over the execution of the constructor, that is, it is automatically called every time an object is new, initializing the object

Class A {int I = 1; the initialization of int initValue;// member variables to the code block to complete the {/ / code block is reflected in this: initializing the member variables with a piece of code before calling the constructor. It is not done when the constructor is called. It is generally used to extract the same part of the construction method. / / for (int I = 0 I < 100 X I +) {System.out.println + = I;}} {System.out.println (initValue); System.out.println (I); / / at this time, 1 int I = 2 System.out.println (I) is printed / the variables in the code block do not conflict with the member variables, but the code block variable System.out.println (I) is preferred. / / print 2 / / System.out.println (j) at this time; / / prompt for illegal backward reference, because initialization of j has not started at this time. / /} {System.out.println ("code block runs");} int j = 2; {System.out.println (j); System.out.println (I); / / variables in the code block are automatically released after running, which does not affect the code outside the code block} A () {System.out.println ("constructor run") }} public class construction code block {@ Test public void test () {AA = new A () }} static code block location: class member location, static-decorated code block function: some initialization of the class is loaded only once, when new multiple objects, only the static code block will be called for the first time, because the static code block belongs to the class All objects share one call: public class static code block {@ Testpublic void test () {C C1 = new C () is automatically called when new an object. C c2 = new C () / / as a result, the static code block is called only once, and all objects of the class share the code block / / generally used for global information initialization of the class / / static code block call / / code block call / / constructor call / / code block call / / constructor call}} class C {C () {System.out.println ("constructor call") } {System.out.println ("code block invocation");} static {System.out.println ("static code block invocation");}} Java code block, constructor (including inheritance relationship) execution order

This is a common interview question. To answer this question, take a look at this example.

There are three categories: a, B, C

Where An is the parent of B, and C has no inheritance only as output

Category A:

Public class A {static {Log.i ("HIDETAG", "A static code block");} private static C c = new C ("A static member"); private C C1 = new C ("A member"); {Log.i ("HIDETAG", "A code block");} static {Log.i ("HIDETAG", "A static code block 2");} public A () {Log.i ("HIDETAG", "A construction method") }}

Category B:

Public class B extends A {private static C C1 = new C ("B static member"); {Log.i ("HIDETAG", "B code block");} private C c = new C ("B member"); static {Log.i ("HIDETAG", "B static code block 2");} static {Log.i ("HIDETAG", "B static code block") } public B () {Log.i ("HIDETAG", "B construction method");}}

Class C:

Public class C {public C (String str) {Log.i ("HIDETAG", str + "Construction method");}}

Execute statement: new B ()

The output is as follows:

I/HIDETAG: a static code block I/HIDETAG: a static member construction method I/HIDETAG: a static code block 2 I/HIDETAG: B static member construction method I/HIDETAG: B static code block 2 I/HIDETAG: B static code block I/HIDETAG: a member construction method I/HIDETAG: a code block I/HIDETAG: a construction method I/HIDETAG: B code block I/HIDETAG: B member construction method I/HIDETAG: B construction method

Draw a conclusion:

The order of execution is as follows: static members of the parent class and code block subclass static members and code block parent class member initialization and code fast parent class construction method subclass member initialization and code block subclass construction method

Note: it can be found that code block and member initialization at the same level are performed from top to bottom in code order.

After reading the demo above, let's take a look at the following question to see if you can handle it.

Look at the following code to find the order of execution:

Class A {public A () {System.out.println ("Construction method of Class 1A");} {System.out.println ("Construction of Class 2A");} static {System.out.println ("static Block of Class 3A");}} public class B extends A {public B () {System.out.println ("Construction method of Class 4B") } {System.out.println ("fast construction of class 5B");} static {System.out.println ("static block of class 6B");} public static void main (String [] args) {System.out.println ("7"); new B (); new B (); System.out.println ("8");}}

The result of execution sequence is 367215421548

Why?

First of all, we need to know the following five points:

Each time the new executes the constructor and the building block.

The contents of the building block are executed before the constructor.

Static blocks of non-main classes are executed only once, when the class is loaded, before the constructor and the building block.

Static blocks in the main class (public class) are executed before main.

In inheritance, when the subclass is instantiated, the constructor of the parent class is executed first, the parent object is generated, and then the subclass constructor is called.

So in the title, because the main class B inherits A, it will load A first, so the first one is the third sentence.

We know from point 4 that 6 will be executed before 7, so the first three sentences are 367.

Then B is instantiated twice, each time his parent class An is instantiated first, and then B is instantiated, and according to points 1, 2, and 5, the order is 2154.

Finally execute 8

So the order is 367215421548.

At this point, the study on "how to use the Class class and object class of Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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