The article directories

  • Java Basic Syntax (7) — Classes and objects
  • A preliminary understanding of classes and objects
  • Classes and instantiation of classes
    • 1. Class definition
    • 2. Instantiate the object
    • 3. How to use the data in the class
  • Members of classes
  • 1. Fields/attributes/member variables
    • (1) Instance member variables
    • (2) Static member variables
  • 2. The method (method)
    • (1) Instance member methods
    • 2. Static member methods
    • (3) toString method
  • 3. Static keyword
    • (1) Modify attributes
    • (2) Modification methods
  • Four, encapsulation
    • (1) Private implementation encapsulation
    • (2) Getter and setter methods
  • 5. Construction method
    • (1) Basic grammar
    • (2) New execution process
    • (3) Grammar rules
    • (4) Matters needing attention
    • (5) This keyword
    • The introduction of this
    • This usage
  • Understand code blocks
  • 1. Static code blocks
  • 2. Example code block
  • 3. Execution sequence
  • Seven, supplement
  • 1. Anonymous objects
  • Eight, to practice
  • Nine,
  • Finished!

Java Basic Syntax (7) — Classes and objects


\

Following the previous blog – Java Basic Syntax (6) – the definition and use of arrays


\

This content introduces the outline

\

\

A preliminary understanding of classes and objects

\

First, classes and objects are very abstract concepts. Let’s start with, what is a class? What is an object?

\

A class is a general term for a class of objects.

An object is an instance of this kind of externalization.

\

Let’s give you some examples:

\

I believe all of you have eaten moon cakes, the mold we make moon cakes is a class, and through this mold can make moon cakes, so in this case, the class is the mold, and the moon cake is the object, so the moon cake is an entity. A template can instantiate an infinite number of objects.

\



\

In other words, a class is equivalent to a drawing of a house. The house we build from this drawing is a concrete object. A drawing can build multiple houses, so a class can instantiate multiple objects.

\



Class

\

What is object oriented, procedure oriented in programming languages?

\

C language is process-oriented, focusing on the process, analyzing the steps to solve the problem, and solving the problem step by step through function calls.

JAVA is object-oriented and focuses on objects, breaking one thing into different objects and relying on the interaction between objects.

\

The difference between object-oriented and procedural

\

Process-oriented focuses on the process, and the behavior involved in the whole process is function.

Object orientation focuses on objects, the subjects involved in the process. It is the logic that connects one functional implementation to another.

\

Let’s take a visual example of object orientation and process:

\

Process-oriented: 1. open the refrigerator 2. put the elephant in 3. close the refrigerator

Object oriented: open refrigerator, store, close are the operation of refrigerator, is the behavior of refrigerator.

The refrigerator is an object, so as long as the operation of the refrigerator has the function, must be defined in the refrigerator.

\

In a nutshell

Object orientation is a way of describing things in the objective world with code (classes). A class mainly contains the properties and behavior of a thing. We will gradually understand the characteristics of object orientation as we go further.

\

Classes and instantiation of classes

\

A class is equivalent to a template, and an object is a sample generated by the template.

We’ve already seen how to use objects through classes, so how do we use them in Java programming? \

1. Class definition

\



\

First note:

A class is made up of fields and methods.

Class names are defined using the big hump form

Member variables are also called fields, attributes, etc.

Let’s implement a concrete class definition:

\

\

Inside the class, we temporarily put a public access qualifier in front of each variable, and in addition to public, we also have private and protected access qualifiers, which we’ll talk about later.

\

Here we define a class of Person, and inside the class we define properties name, sex, age, and methods.

\

Matters needing attention

1. Unlike the previous method, this method does not contain the static keyword. We’ll explain static in more detail later.

2. When a member variable in a class is not defined, the default value is 0 of its type

\

Take the data from the class in the figure above

Value of a member variable when uninitialized

\

2. Instantiate the object

\

We know that objects are instantiated by classes. This is the example above.

Person, which is the variable name defined, = on the right hand side we instantiate an object with the new keyword.

Structure in memory at this time:

Of course, a class can create multiple instantiated objects:

\

\

3. How to use the data in the class

\

We said that we access objects through a class, so how do we manipulate members of that class?

For example, we want to initialize the data in the class we defined above and call the member methods in the class.

\

Code implementation:

\

\

Compiler implementation effect:

\

\

Note:

\

1. The new keyword is used to create an instance of an object.

2. Use. To access properties and methods in objects.

3. You can create multiple instances of the same class.

\

Members of classes

\

Members of a class can contain fields, methods, code blocks, inner classes, interfaces, and so on.

Here we highlight the first three.

\

1. Fields/attributes/member variables

\

(1) Instance member variables

\

A variable in a class, but defined outside the method. Such variables are called “fields” or “attributes” or “member variables” (you can call them all three, but they are generally not strictly distinguished).

Instance member variables are used to describe what data is contained in a class.

\

\

Execution Result:

\

Matters needing attention

1. Access the fields of the object using. Access includes both read and write.

2. Fields of an object that have no explicit initial value are set to a default initial value.

3. Instance member variables are accessed inside the object.

\

Default rule

1. For various numeric types, the default value is 0.

2. For Boolean types, the default is false.

3. The default value is null for reference types (String, Array, and custom classes)

\

(2) Static member variables

\

A class also has a variable called a static member variable.

\



\

The static member of the high variable is static.

\

Static member variables are different from instance member variables. Instance member variables are accessed through objects. Where is the object stored? In a heap. Static member variables, on the other hand, are accessed directly through the class and are stored in the method area.

\

Accessing static member variables:

\



\

When accessing a static variable in a class, we don’t need a new object, because static variables don’t depend on objects for access.

\

2. The method (method)

\

(1) Instance member methods

\

Methods describe the behavior of an object.

Class method creation:

\

\

Member method calls:

Member methods also rely on objects for access.

\

\

Execution Result:

\

\

2. Static member methods

\

Classes also have a method called static member methods.

\

Static method definition:

In the figure above, the drink() method is a static member method, prefixed to the return value by static, otherwise in the same form as the instance member variable.

\

Static member method calls:



\

Note:

\

Static member methods in a class are accessed directly through the class, independent of the object.

\

(3) toString method

\

In the class, we define many member variables and so on. When we want to show their contents first, we need to write a show () method to show them, but we have the corresponding toString method in the class, which converts the member variable to a string and uses this method to print the display.

\

ToString is a method provided by the Object class. The Person class we created inherits from the Object class by default. We can override toString to implement our own version of the conversion string method.

\

Alt +f12(insert)

\

The toString method displays the contents of a member variable:

\

\

Execution Result:

\

Matters needing attention:

The toString method is called automatically at println.

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

\

3. Static keyword

\

(1) Modify attributes

\

Java static properties are class-specific, not instance specific. In other words, different instances of the same class share the same static property.

\

Let’s look at a string of code like this:

\

\

What is the result of this string of code execution?

\

Let’s break it down one by one:

We created a Test Demo class with two variables, instance member variable A and static member variable count.

\

The code in main is in memory:

First, an object T1 is created, which creates a chunk of memory 0x222 in the heap, a++, where a is now 1

\

Count ++, count does not depend on the object, it is stored in the method area, and there is only one copy, so count=1.

\

Then an object T2 is created, which creates a chunk of memory 0x111 in the heap, a++, where a is 1

\

Count plus plus, I’m going to add 1 to count, so count is equal to 2.

\

Output result:

\

(2) Modification methods

\

If the static keyword is applied to any method, the method is called static.

\

Static methods belong to classes, not objects that do not belong to classes.

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

Static methods have access to static data members and can change their values.

\

Let’s look at the following code:



Execution Result:



Therefore, you cannot use non-static variables in static member methods.

\

Static member method calls:



Static member methods are called directly from the class and do not depend on the object. Therefore, the call can be made without creating an instance object.

\

Note 1:

Static methods have nothing to do with instances, but with classes. So this leads to the following:

Static methods cannot directly use non-static data members or call non-static methods (which are instance-dependent).

\

Note 2:

Static. Static. Static. But whether a method is static or not depends on the situation.

The main method is static.

\

Four, encapsulation

\

There are often two roles involved when we write code: the implementer of a class and the caller of a class.

The essence of encapsulation is that the caller of a class doesn’t have to know much about how the implementer of the class implements the class, just how to use it.

This reduces the cost of learning and using the class consumer, thereby reducing the complexity.

\

What is encapsulation?

Encapsulation is the use of private to decorate properties and variables.

\

(1) Private implementation encapsulation

\

Private is an access restriction modifier, meaning private. So variables decorated with private can only be used inside the class and cannot be accessed through instance objects. As shown below:

\

\

So private means that this variable can only be accessed within the class.

So we still have a question, why do we have to use private encapsulation?

\

The keywords private and public indicate access control.

Member variables or member methods that are public can be used directly by class callers.

Member variables or member methods that are private cannot be used by class callers.

\

In other words, users of a class don’t need to know or care about which private members a class has. This allows class callers to use the class at a lower cost.

Let’s use code to explain why private is encapsulated.

\

If we use public for all of them



\

Execution Result:

\

\

Such code results in a consumer of the class (the code for the main method) having to understand the internal implementation of the Person class in order to use it. Learning costs are high.

Once the implementer of a class changes the code (for example, by changing name to myName), the user of the class will need to modify his code extensively, which is costly to maintain.

\

We wrap it in private and provide public methods for the class’s callers to use

\



\

The field is already decorated with private. Class callers (in the main method) cannot be used directly. Instead, use the show method. At this point, the user of the class does not need to know the implementation details of the Person class.

\

At the same time, if the class implementer changes the field name, the class caller does not need to make any changes (the class caller has no access to fields like name and age).

\

Note:

Private can modify methods as well as fields

Normally we would make fields private, but whether methods need to be public depends on the situation. In general, we want a class to only provide “necessary” public methods, not make all methods public.

\

(2) Getter and setter methods

\

When we use private to decorate a field, we cannot use the field directly.

To obtain or modify the private property, you need to use getter/setter methods.

\

Implement getter and setter methods:

\



\

Matters needing attention:

\

GetName is the getter method that gets the value of the member.

SetName is the setter method that sets the value of this member.

When the parameter name of a set method is the same as the name of a member attribute in the class, this is self-assignment. This is a reference to the current instance.

Not all fields must provide setter/getter methods, but it is up to you to decide which method to provide.

You can use Alt + INSERT (or Alt + F12) to quickly generate setter/getter methods in IDEA. Automatically generate setter/getter methods in VSCode using the right mouse button menu -> source actions.

\

Quick Settings for getters and setters

Alt + insert boot

\

\

5. Construction method

\

First of all, what is a constructor?

\

\



Results after execution;

\

\

So what’s the use of constructors?

\



\

So, we didn’t write this constructor when we instantiated the object before, why can we instantiate the object?

\



\

(1) Basic grammar

\

The constructor is a special method that is automatically called when a new object is instantiated using the keyword new to perform initialization.

\

(2) New execution process

\

1. Allocate memory space for objects

2. Invoke the object constructor

\

(3) Grammar rules

\

1. The method name must be the same as the class name

2. The constructor has no return value type declaration

3. Each class must have at least one constructor (if not explicitly defined, the system automatically generates a no-parameter constructor).

\

(4) Matters needing attention

\

If no constructor is provided, the compiler generates a constructor with no arguments by default

If a constructor is defined in a class, the default no-argument construct is no longer generated.

The constructor supports overloading. Rules are the same as normal method overloading.

\

Multiple constructors can be supported within a class.

Use of multiple constructors:

\



Execution Result:

\

(5) This keyword

\

In the previous code, we used the this keyword for some variables, so let’s look at what this does.

Important: This represents a reference to the current object, and can be used to access the object’s fields and methods.

\

The introduction of this

\

Why introduce this?

Here’s a code comparison:



So we can see the benefits of using this by comparison.

\

This usage

\

The use of this in the class: \

\

this.data

Usage:

1. Access the member variables of the current object

2. Do not access static member variables

2. Static methods cannot have this inside.


\

this.func()

Usage:

1. Access the member methods of the current object


\

this()

Usage:

1. Access the current object’s own constructor

2. Can only be used in constructors

3. Use only one this ()

3. Can only be placed in the first line of the constructor

\

Understand code blocks

\

What is a code block?

A piece of code defined using {}.

According to the position and keyword defined by code block, it can be divided into the following four types:

\

1. Normal code block 2. Construction block 3. Static block 4. Synchronous code block (more on this later in the multithreading section)

\

Today’s focus is on building blocks and static blocks.

Ordinary blocks, we should all know, are code blocks defined in methods.

\

1. Static code blocks

\

Use static defined code blocks. Typically used to initialize static member properties.

Use of static code blocks:

\

\

Execution Result:

\

Note :\

A static code block executes only once and first, no matter how many objects it generates.

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

\

2. Example code block

\

Constructor block: A block of code (without modifiers) defined in a class. Also called: instance code block. Construct blocks are typically used to initialize instance member variables.

\

Example code block usage:

\

Execution Result:



\

Note: Instance code blocks take precedence over constructor execution.

\

3. Execution sequence

\

What is the sequence of code execution when static and instance blocks run together?

\

As follows:

We write code blocks statically 1, instance blocks statically 2.

\

\

Execution Result:

\



Therefore, according to the results of implementation, we come to the conclusion:

\

1. After the static code block completes execution, the instance code block (constructor block) executes, and then the constructor executes.

\

What is the order in which static blocks are executed?

We switch the order of static ones and static twos.

\

\

Execution Result:



\

We can also draw a conclusion from this result:

\

Static code blocks are executed in the order in which we write code, in order.

\

Seven, supplement

\

1. Anonymous objects

\

Anonymous simply means an object without a name.

\

Definition:

\

Objects without references are called anonymous objects.

\

Anonymous objects can only be used when creating objects.

If an object is only used once and no longer needs to be used, consider using anonymous objects.

Use of anonymous objects:

\



\

This is calling methods through anonymous objects.

\

Eight, to practice

\

1. Complete the class Calculator and its addition, subtraction, multiplication and division operations.

\

2. Exchange the values of two variables. Requirement: The values of the arguments need to be swapped.

\

In my blog Java classes and Objects Exercise, I hope you can practice today’s content.

\

Nine,

\

Summary of main contents

\

A class can produce an infinite number of objects. A class is a template and an object is a concrete instance.

Attributes defined in a class are roughly divided into several categories: class attributes and object attributes. Static data attributes are called class attributes

A method is called a class method, which is independent of the object. We can call its properties or methods only by the name of the class.

Static code blocks take precedence over instance code blocks, and instance code blocks take precedence over constructors. The this keyword represents a reference to the current object. It’s not the current object.


\

Well, this time the Java basic syntax (seven) — class and object knowledge to share here, thank you for your appreciation and attention!


\

Thank you!!




\

Finished!