Chapter one is object oriented

Xiao Bai: Java is a fully object-oriented programming language! Huh? What is process orientation? What is object orientation?

Big man: Before we get into the learning part, it will be very helpful to know the concepts of process orientation and object orientation. Don’t worry, I’ll talk to you about it.

Process oriented — step oriented

Process orientation is to analyze the steps needed to achieve the requirements, implement these steps step by step through functions, and then call

Object-oriented — behavioral

Object orientation is to divide the whole requirement according to characteristics and functions, and encapsulate these common parts into objects. The object is not created to complete a certain step, but to describe the behavior of something in the steps of solving problems

Xiao Bai: Process oriented is quite clear, object oriented is too difficult to understand it (cried)

Big guy: Let me give you another example to explain

Table tennis examples – to help understand

Let’s start with a requirement:

Design a pool game (skip kick-off and consider only the middle)

Process-oriented thinking:

1. Palyer1 shot

2. Achieve the screen hitting effect

3. Judge whether the goal is scored and effective

4. Palyer2 shot

5. Achieve the screen hitting effect

6. Judge whether the goal is scored and valid

7. Return to Step 1

8. Output game results

This requirement is complete by implementing the above steps step by step through functions.

Object-oriented thinking:

After observation, we can see that there are many commonalities in the above process

So we put all these common parts together into a universal structure

  1. Player systems (including Palyer1 and Palyer2)

  2. Batting effect system, responsible for showing the user the picture of the game

  3. Rule system, judging whether there is a foul, win or lose, etc

We will tedious steps, through behavior, function, modular, which is object-oriented, we can even use the program, respectively, to quickly achieve 8 ball and snooker of different games (only need to modify the rules, player system, hitting effect system are consistent)

Pros and cons of procedural versus object orientation:

Process oriented

Advantages: Performance is superior to object-oriented because classes need to be instantiated at call time, which is too expensive.

Disadvantages: not easy to maintain, reuse, expansion

Purpose: microcontroller, embedded development, Linux/Unix and other high performance requirements

object-oriented

Advantages: easy to maintain, easy to reuse, easy to expand, due to the characteristics of object-oriented encapsulation, inheritance, polymorphism, can design a low coupling system, make the system more flexible, more easy to maintain ** Disadvantages: ** performance is lower than process oriented

Low coupling, simple understanding is that modules and modules as independent as possible, the relationship between the two as simple as possible, as far as possible to independently complete some sub-functions, which avoids the problem of affecting the whole body. This part will be systematically sorted out and summarized after the end of object-oriented learning.

Through textbooks only after the sample is unable to realize the existing problems in the process oriented, in a few small routines, process-oriented feeling will be more simple, but once facing larger projects, we need to write N functionally similar function, more and more functions, code quantity is more and more, Bug also begins on the road.

1.1 Classes and objects

How does object-oriented thinking manifest itself in Java? That’s through classes and objects

A class is a collection of related properties and behaviors. Is an abstract concept. An object is a concrete representation of that kind of thing. A concretely existing individual.

Member variable The property of a thing

Member method behavior of things

So how do we understand these concepts?

A class is a description of individuals with common characteristics and similar behaviors.

For example, Xiao Li and Lao Zhang both have names, ages, height, weight and other attributes, and they can chat, exercise and other similar behaviors.

Due to the two people have the common place, so we put it of abstracting, defined as a class – human beings, and xiao li, Lao wang is the individual in the class (object), and the existence of the individual is the true specific, light mentioned people, you only know which properties should be behavior, but you don’t know his specific some values, For example, you know that he is “human” so he should have a name and age, but you don’t know his name or how old he is. But xiao Li and Lao Wang these two concrete objects, can actually know Lao Wang this year 30 years old, height 175 equivalent.

Combine the above examples to summarize:

Member variables are used to describe the attributes of the class, such as the name, age and so on

The member method is used to describe the behavior of things, such as humans being able to chat, move, etc

1.1 Definition and usage of _1 class

We learned the basic definitions and concepts of classes and objects

Let’s use an example to see how to define a class

A: Class definition

Member variables: Defined in the same format as normal variables, but in different locations, inside classes and outside methods.

Member methods: Define the same format as normal methods, except that static is removed.

B: Create and use classes

A: Create an object format

Class name Object name = new class name ();

Eg: Person p = new Person();

B: How do you use member variables and member methods

Object name. Member variable

Object name. member method ()

Eg: p.r eading ();

p.sleeping();

In fact, we can see that the definition of the class is very simple, combining the previous knowledge, just a few different positions, and the meaning of each part of the creation of the object format will be explained in the following.

Let’s start with one topic

You often hear the term local variable. Does it have anything to do with a member variable in a class?

1.1 differences between member variables and local variables:

(1) Different positions in the class

Member variables: outside of a method in a class

Local variables: in a method definition or declaration

(2) Different locations in memory

Member variables: in the heap

Local variables: on the stack

(3) Different life cycles

Member variables: They exist as the object is created and disappear as the object disappears

Local variables: exist as the method is called and disappear as the method is called

(4) Different initialization values

Member variables: Have default values (more on this below)

Local variables: there are no default values. They must be defined, assigned, and then used

About the initialization problem we explain in more detail below, but now I have one more question, in our learning Java memory allocation, have so a > words, “heap memory used to store the new objects created and array”, in other words the object exists in the heap, and member variables exist in class is a class and object > individual, So member variables also exist in the heap, so the problem is, when we deduce it in the same way, we find that methods also exist in objects as member variables. This is clearly different from our definition above

A class can create n different object, when we are new to an object, the object entity, has the memory space allocated on the heap, as a member of the class > variables vary in different objects (for example, xiao li and wang’s name), all need their respective storage space, so the members of the class variables is stored as object in the heap, Since the methods of a class are common to all objects, local variables in the method are not created when the object is created, and are pushed only when the object uses the method.

1.1 problems of _3 formal parameters:

We know that the heap holds new objects and arrays, both of which are reference types

When we talked about arrays, we talked about primitive types and arrays as reference types, and how formal parameters affect actual parameters

Jump – Chapter 3 3.3_1 Parameter Transfer Problems

After we look at objects, let’s continue to look at this problem

Base type: changes in formal parameters do not affect actual parameters (value passing) Reference type: Changes in formal parameters directly affect actual parameters (reference passing)

1.1_4 Anonymous Objects (Understood)

Let’s start by looking at how to create anonymous objects, okay

(1) An object without a name

(2) Application scenarios

A: Call A method, only once.

B: Can be passed as an actual parameter

Benefits: Anonymous objects are garbage after being called and can be collected by the garbage collector, making it easier to write.

Note: If you call multiple members of an object, you must give the object a name (s in the figure above), using the normal method of creating an object

Let’s take a look at an example and see how we can actually use anonymous objects, okay


1.1_5 Encapsulation overview and use

Let’s start with a quick example:

For example, when the dormitory is very hot in summer, we (users) only need to operate the remote control to use the air conditioner, without knowing how the air conditioner works inside

Now I don’t have much knowledge, so I don’t have a very deep understanding of the concept of encapsulation. Don’t worry, go over it first, and I will write a specific article about the meaning and problems of encapsulation. Now I only need to have an impression.

Encapsulation overview: Hides the properties and implementation details of an object and provides only public access

Encapsulation benefits:

· Hide implementation details and provide public access

· Improved code reusability

· Improved security

Encapsulation principle:

· Hide content that doesn’t need to be made public

· Hide attributes and provide public method access to them

Thinking process:

Assigning a value to a member variable from an object allows assigning some illegal data

This is unreasonable. So you should evaluate the data before assigning it

StudenDemo is a test class that typically creates objects and calls methods

So this judgment should be defined in the Student class. Logical statements are required

Logical statements should be defined in methods. So provide a method in the Student class to validate the data

But if you simply don’t call the method to assign, assign directly

And then our methods didn’t work

So we have to force my method instead of calling a member variable directly

Java provides a keyword private for this

Private: Private, can modify member variables and member methods

Members decorated by private can only be accessed in the class, so outsiders who want to manipulate member variables in the class must do so by calling methods in the class


1.1_6 Access modifier

Client programmer: A class consumer who uses data types in his application. His goal is to collect classes for rapid application development.

Class creator: A programmer who creates a new data type with the goal of building a class.

Access control exists for:

A. Keep client programmers out of reach where they shouldn’t be;

B. Allows library designers to change the way classes work internally without worrying about affecting client programmers

The four Java keywords are public, protected, default, and private

(They decide who can use what is defined next)

Scope of application < The smaller the scope of access, the higher the security >

Access permissions class package A subclass Other packages
public Square root Square root Square root Square root It’s available to anyone
protect Square root Square root Square root Inherited classes have access and the same privileges as private
default Square root Square root Inherited classes have access and the same privileges as private
private Square root An element that is not accessible to anyone other than the type creator and the internal methods of the type

1.1_7 Private Application standard cases

This keyword can be used to improve (it is usually used to improve)

The contents of this will be introduced in a moment


1.1_8 Overview and application of this keyword

The call can only be made by the object name, which in this case should represent an object of student

This: Represents the object reference of the class

Remember: This represents the object on which the method is called

Applies: Local variables hide member variables (added later)

1.2 Construction method

The constructor has the same name as its class, but the constructor does not return a value.

Constructors are usually used to assign initial values to instance variables of a class, or to perform other steps necessary to create a complete object

How do you understand that?

The constructor is used to initialize an object when it is created.

So what does initialization mean?

Do we know that a constructor is also called a constructor, and that’s what it does to initialize a class, so when it’s called, it initializes the member with a value, when it’s called with a parameter, it passes the value of the parameter to the member, and when it’s called with no parameter, it initializes the member with some default value

Such as:

Private String name;

private int age;

public bool flag;

The above three member variables are initialized by default when they are constructed without arguments

Name = null; Age = 0; Flag = false;

Note:

A: If we do not give A constructor, the system will automatically provide A no-parameter constructor

B: If we give the constructor, the system will no longer provide the default no-parameter constructor

If we want to use the parameterless constructor at this point, we must give it ourselves. It is recommended to always give the parameterless constructor (so we are used to giving both parameterless and parameterless constructors in our classes).

There are two ways to assign a value to a member variable:

A:setXxx()

B: Construction method

Here we have to mention that get and set methods, in the future when writing code, we need to use frequently, in fact, here reflects the encapsulation, do not let the user directly operate members, can play a role in security, the specific content can see the previous part of the encapsulation knowledge

The constructor is used to initialize the object when it is created by passing in the necessary parameters.

The setter/getter controls whether a property can be read or written

The two are not contradictory

The class initialization process is described as follows:

Class initialization process

Student s = new Student(); What’s going on in memory?

· Load the Student. Class file into memory

· Create space for S in stack memory

· Create space in heap memory for student objects

· Member variables of the student object are initialized by default

· Display initialization of member variables of the student object

· Assign values to member variables of the student object through constructors

· After the initialization of the student object, assign the address of the object to the S variable

1.3 Static keyword

Static keyword Precautions

A: There is no this keyword in static methods

Static is loaded as the class is loaded; this is created as the object is created; static precedes the object

B: Static methods can only access static member variables and static member methods

Static method:

**A: Member variables: ** Can only access static variables

**B: member methods: ** Only static member methods can be accessed

Non-static methods:

**A: Member variables: ** can be static or non-static

**B: Member methods: ** can be static or non-static member methods

Why can’t static methods access non-static methods?

Because static methods are loaded as the class is loaded, static is better than object existence. You want to access something that is not static, but it may not exist yet.

To sum up: static can only access static

1.4 Static and member variables

To strike while the iron is hot, let’s make some distinctions between static and member variables

Belong to different

· Static variables are classes, so they are also called class variables

· Member variables belong to objects. So also called instance variables (object variables)

· Different locations in memory

· Static variables are stored in the static section of the method area

· Member variables are stored in heap memory

· Memory time is different

· Static variables are loaded as the class is loaded and disappear as the class disappears

· Member variables exist as the object is created and disappear as the object disappears

· Different calls ·

· Static variables can be called either by class name or by object

· Member variables can only be called by object names

One is to call a member method from an object

Method 2 is to call a member method with a class (recommended method 2 [write the corresponding member method static]).

Call the member method if you don’t want the user to create an object:

All you need to do is make the constructor private, and the outside world can’t create the object

Under the same folder, the class defines that two folders and one folder are the same

1.4 Make documentation notes and instructions

(a)

Javadoc tool D: format javadoc -d directory -author -version arrayTool. Java directory: you can write the path of a folder to create a help document. No public or protected classes can be documented: tell us the class has insufficient permissions (solution: add public before class)

(2)

API(Application Programming Interface)

Application Programming Interfaces (Help documentation)

The Jdk can help you look up classes, methods, and parameter descriptions. It is also important to learn how to consult the documentation (download from the web).

Next interview yourself using a class by consulting the documentation

Math class

A: It’s A class that operates on math

B: There is no constructor because its members are static

C: Generates random numbers

Public static double random(): [0.0,1.0)

D: How to generate a random number between 1 and 100

int number = (int)(Math.random()*100)+1;

E: Guess the numbers

1.5 the code block

Let’s move on to the last point in this section

(1) code enclosed in {}.

(2) categories:

A: Static code blocks

Concept: In Java classes (there can be no static code blocks in methods)

A code block declared with the static close key and {} :

Execution: Static code blocks run when the class is loaded, only once, and precede various code blocks and constructors.

What it does: In general, static code blocks are needed if some code needs to be executed at project startup. For example, many configuration files and other resources that need to be loaded to start a project can be put into static code blocks.

Class data is initialized only once.

B: Construct code blocks

** Code blocks declared in Java classes using {} (the distinction between static and static blocks is missing the static keyword) :

Execution: The constructor block is called when the object is created, once each time the object is created, but takes precedence over the constructor execution.

Function: Similar to the function of constructors, objects can be initialized, and whenever an object is created, the construction block is executed once. Constructors, on the other hand, are not always executed for each object (multiple constructors are used to initialize objects with different parameters).

The same code from multiple constructors can be placed here, and the constructor block is executed before each constructor is executed.

C: Local code block

It is used to limit the life cycle of variables and release them early to improve memory utilization.

Static code block, construct code block, construct method order problem

· Static code block > Construct code block > constructor

The end:

If there is any inadequacy in the content, or wrong place, welcome everyone to give me a message to put forward opinions, crab crab everyone! ^_^

If it helps you, follow me!

We don’t know each other here, but we are working hard for our dreams

A adhere to push original Java technology public account: ideal more than two days