Thinking logic of computer programs (13), thinking Logic

Source: Internet
Author: User
Tags gety modifiers natural logarithm

Thinking logic of computer programs (13), thinking Logic

Class

In the previous section, we introduced the basic principles of function calling. In this section and the next sections, we will explore the world of classes.

Programs mainly involve data and operations on data. To facilitate understanding and operation, advanced languages use the data type concept. Different data types have different features and operations, java defines eight basic data types, four of which are integer byte/short/int/long, two floating point float/double, and one is true or false boolean, a char is a type of character. Other types of data are expressed by the class concept.

In the first two sections, we temporarily regard the class as a function container. In some cases, the class is basically a function container, but the class is more of a custom data type, we will first talk about classes from the perspective of containers and then from the perspective of custom data types.

Function container

Let's take a look at an example. The Math class in Java APIs mainly contains several mathematical functions. The following table lists some of them:

Math Function

Function

Int round (float)

Four sets and five entries

Double sqrt (double)

Square Root

Double ceil (double)

Rounded up

Double floor (double)

Round down

Double pow (double a, double B)

B power of

Int abs (int)

Absolute Value

Int max (int a, int B)

Maximum Value

Double log (double)

Natural logarithm

Double random ()

Generates a random number greater than or equal to 0 and less than 1


Using these functions, you can simply add Math. To the front, for example, Math. abs (-1) returns 1.

These functions all have the same modifier, public static.

Static indicates a class method, also called a static method. It is opposite to a class method. The instance method does not have a static modifier and must be called through an instance or an object (to be described later). The class method can be called directly by class name without the need to create an instance.

Public indicates that these functions are public and can be called from outside. Private is the opposite of public. If it is private, it indicates private. This function can only be called by other functions in the same class, but not by external classes. In the Math class, a function Random initRNG () is private, which is called by the public Method random () to generate Random numbers, however, it cannot be called outside the Math class.

Declaring a function as private can avoid misuse of the function by external classes. The caller can clearly know which functions can be called and which functions cannot be called. Class implementers encapsulate and hide internal implementation details through private functions, and callers only need to care about public. It can be said that private Encapsulation and hiding of internal implementation details to avoid misoperations are a basic way of thinking for computer programs.

In addition to the Math class, let's take a look at Arrays. Arrays contains many functions related to Array Operations. The following table lists some of them:

Arrays Functions

Function

Void sort (int [])

Sort by ascending order and an integer Array

Void sort (double [])

Sort by ascending order, floating point Array

Int binarySearch (long [] a, long key)

Binary Search, array in ascending order

Void fill (int [] a, int val)

Assign the same value to all array elements

Int [] copyOf (int [] original, int newLength)

Copy Array

Boolean equals (char [] a, char [] a2)

Determine whether the two arrays are the same

Here we will regard classes as function containers. More importantly, from the perspective of language implementation, Math and Arrays can also be seen as custom data types, it represents the mathematical and array types respectively. The public static function can be regarded as an operation that can be performed by the type. Next, let's discuss the Custom Data Types in more detail.

Custom Data Type

We regard the class as a custom data type. The so-called custom data type is a type other than the eight basic types used to represent and process data other than the basic types.

A data type consists of its contained attributes and the operations that can be performed by this type. attributes can be classified into attributes of the type or specific data. Similarly, operations can also be divided into operations that can be performed by the type itself, or operations that can be performed by a specific data.

In this way, a data type is mainly composed of four parts:

  • Attributes of a type, which are reflected by class variables.
  • Operations that can be performed by the type itself are reflected by the class Method
  • Attributes of a type instance, which are reflected by instance variables
  • Operations that can be performed by type instances

However, for a specific type, each part does not necessarily exist, and the Arrays class only has class methods.

Both class variables and instance variables are called member variables, that is, class variables are also called static variables or static member variables. Both class methods and instance methods are called member methods, and they are also class members. Class methods are also called static methods.

Class methods we have seen above. The methods defined in the Math and Arrays classes are class methods. The modifiers of these methods must be static. The following describes the class variables, instance variables, and instance methods.

Class variable

Attributes of a type are embodied by class variables and often used to represent constants of A type. For example, Math class defines two constants commonly used in mathematics, as shown below:

public static final double E = 2.7182818284590452354;public static final double PI = 3.14159265358979323846;

E indicates the base number of the natural logarithm in mathematics. The natural logarithm has important significance in many disciplines. PI indicates the circumference rate π in mathematics. Like the class method, class variables can be accessed directly by class names, such as Math. PI.

The modifiers of these two variables are also public static, which indicates that external access is allowed, and static indicates that they are class variables. Private is the opposite of public, indicating that variables can only be accessed within the class. Compared with static, there is no static modifier for instance variables.

Here there is an additional modifier final, which represents a constant when modifying a variable, that is, the variable cannot be modified after being assigned a value. Using final can avoid misoperations. For example, if someone accidentally changes the value of Math. PI, many related calculations may fail. In addition, the Java compiler can perform some special optimization on final variables. Therefore, if the value of the data is not changed, add the final modifier.

Static modifiers are required for class variables, but public and final are not required.

Instance variables and instance methods

An instance is a real example. An instance variable represents the attributes of a specific instance, and an instance method represents the operations that a specific instance can perform. If the subscription number is regarded as a type, the "programming" subscription number is an instance. The Avatar, function introduction, and published articles of the subscription number can be viewed as instance variables, changing the Avatar, modifying the function, and publishing new articles can be seen as an instance method. Compared with the basic type, int a; in this statement, int Is the type, and a is the instance.

Next, we will further understand the custom data types by defining and using classes.

Define the first class
We define a simple class to represent a point in the plane axis. The Code is as follows:

class Point {    public int x;    public int y;        public double distance(){        return Math.sqrt(x*x+y*y);    }}

Let's explain:

public class Point

It indicates that the type is Point and can be publicly accessed by the outside world. This public modifier seems redundant and cannot be accessed by external users? Here, private cannot be used to modify the Point. But the modifier can be absent (that is, leave it blank), indicating a package-level visibility. We will introduce it in subsequent chapters. In addition, classes can be defined inside a class, in this case, you can use the private modifier. We will also introduce it in subsequent chapters.

public int x;public int y;

Two instance variables, x and y, are defined to represent the x coordinate and y coordinate, which are similar to class variables. modifiers also have public or private modifiers, which indicate similar meanings, public indicates that the instance can be accessed from outside, private indicates that the instance is private and cannot be accessed directly from outside. The instance variable cannot have a static modifier.

public double distance(){    return Math.sqrt(x*x+y*y);}

Defines the instance method distance, indicating the distance from the point to the coordinate origin. This method can directly access the instance variables x and y. This is the biggest difference between the instance method and the class method. Both the instance method and the class method can have parameters, operations, and return values, however, the class method can only operate on parameters and variables defined in the method, while the instance method can directly operate on instance variables, read or modify.

What does the instance method mean by directly accessing instance variables? In fact, there is an implicit parameter in the instance method. This parameter is the instance itself in the current operation and directly operates the instance variable. It also needs to be done through the parameter. We will explain it further later.

Use the first class

Defining a class is similar to defining a function. It does not do anything, allocate memory, or execute code. The method to be executed must be called, and the instance method is called. First, an instance is called an object, which may be used in turn. The following code demonstrates how to use it:

public static void main(String[] args) {    Point p = new Point();    p.x = 2;    p.y = 3;    System.out.println(p.distance());}

Let's explain:

Point p = new Point();

This statement contains the Declaration and value assignment of the Point type. It can be divided into two parts:

1 Point p;2 p = new Point();

Point p declares a variable called p, which is of the Point type. This variable is similar to the array variable, both of which have two memories, one storing the actual content and the other storing the actual content. The declared variable itself only allocates memory space for the storage location, which does not point to any actual content. Because such variables and array variables do not store data, but only store the location of the actual content, they are also called reference type variables.

P = new Point (); creates an instance or object and assigns the value to the Point Variable p. It does at least two things:

Unlike the local variables defined in the method, a default value is assigned to all instance variables when an object is created, which is similar to that when an array is created, the default value of the numeric type variable is 0, the boolean value is false, the char value is '\ u000000', the referenced type variables are all null, and null is a special value, indicating that no object is directed. These default values can be modified. We will introduce them later.

p.x = 2;p.y = 3;

Assign a value to the object variable in the syntax format: object variable name. member name.

System.out.println(p.distance());

Call the instance method distance and output the result. Syntax: object variable name. method name. The actual operation on instance variables in the instance method is the data of the object p.

When introducing basic types, we first define data, then assign values, and finally operate. The custom types are similar to the following:

  • Point p = new Point (); defines data and sets the default value.
  • P. x = 2; p. y = 3; yes value assignment
  • P. distance () is a data operation.

It can be seen that access to instance variables and instance methods is carried out through objects, and access and operation of internal data through objects is a basic object-oriented thinking. In this example, the internal data x and y are directly operated through the object. This is a bad habit. Generally, the instance variable should not be declared as public, instead, the instance variables should be operated only through the object method. The reason is that, in order to reduce misoperations, direct access to the variables cannot perform parameter checks and control, but modification through methods is allowed, you can check in the method.

Modify the default value of a Variable

Previously, we said that all instance variables have a default value. If you want to modify this default value, you can assign a value while defining the variable, or put the code into the initialization code block, and the code block is surrounded, as shown in the following code:

int x = 1;int y;{    y = 2;}

The default value of x is set to 1, and the default value of y is set to 2. When creating an object, the initialization is called before the code in the constructor is executed.

Static variables can also be initialized as follows:

static int STATIC_ONE = 1;static int STATIC_TWO;{    STATIC_TWO = 2;    }

Modify class-change instance variable to private

We mentioned above that the instance variable should not be declared as public. Next we will modify the class definition, define the instance variable as private, and operate the variable through the instance method. The Code is as follows:

class Point {    private int x;    private int y;    public void setX(int x) {        this.x = x;    }        public void setY(int y) {        this.y = y;    }        public int getX() {        return x;    }        public int getY() {        return y;    }        public double distance() {        return Math.sqrt(x * x + y * y);    }}

In this definition, we add four methods. setX/setY is used to set the value of the instance variable. getX/getY is used to get the value of the instance variable.

The keyword "this" must be introduced here. this indicates the current instance. In the statement "this. x = x;, this. x indicates the instance variable x, while x on the right indicates x in the method parameter. As mentioned above, there is an implicit parameter in the instance method, which is this. Without ambiguity, you can directly access the instance variables. In this example, if both variables are named x, you must add this to eliminate ambiguity.

These four methods seem redundant. Isn't direct access to variables more concise? As we mentioned above, function calls are costly. In this example, the meaning is indeed not very big. In fact, the Java compiler generally converts calls to these methods to directly access instance variables to avoid the overhead of function calls. However, in many cases, function calls can encapsulate internal data to avoid misoperations. we generally do not define the member variables as public.

The code for using this class is as follows:

public static void main(String[] args) {    Point p = new Point();    p.setX(2);    p.setY(3);    System.out.println(p.distance());}

Change direct access to instance variables to method calls.

Modify class-introduce Constructor

When initializing an object, we assign values directly to each variable. A simpler method is to assign initial values to instance variables, that is, the constructor method. Let's take a look at the code first, add the following code to the Point class definition:

public Point(){    this(0,0);}public Point(int x, int y){    this.x = x;    this.y = y;}

The two are constructor methods, which can have multiple constructor methods. Unlike general methods, constructor has some special features:

  • The name is fixed and the name is the same as the class name. This is easy to understand. This user and the Java system can easily know which constructor methods are used.
  • No return value, and no return value. This rule is probably because the return value is useless.

Like normal methods, constructor methods can also be overloaded. The second constructor is easier to understand. Use this to assign values to instance variables.

We will explain the first constructor. this (0, 0) means to call the second constructor and pass the 0, 0 parameter. We explained earlier that this indicates the current instance, you can use this to access instance variables. this is the second usage of this and is used to call other constructor methods in the constructor.

This call must be placed in the first line. this rule should also be used to avoid misoperation. The constructor is used to initialize the object. If you want to call another constructor, then, make adjustments based on the actual situation. If you initialize a part and call another part, your modifications may be overwritten.

In this example, the second constructor is called through this (0, 0) without parameters. this call is redundant because the default values of x and y are 0, you do not need to assign values separately. Here we mainly demonstrate its syntax.

Let's take a look at how to use the constructor. The Code is as follows:

Point p = new Point(2,3);

This call can set the values of instance variables x and y to 2 and 3. When we introduced new Point (), we mentioned that it has done at least two things: allocating memory and setting default values for instance variables. here we need to add one thing, is to call the constructor. The call constructor is part of the new operation.

Through the constructor, you can assign values to instance variables more concisely.

Default constructor

Each class must have at least one constructor, which is called during object creation through new. However, the constructor can be omitted if there is no operation to do. The Java compiler automatically generates a default constructor without any specific operations. But once the constructor is defined, Java will not automatically generate the default one. What does it mean? In this example, if we only define the second Constructor (with parameters), the following statement:

Point p = new Point();

An error is reported because the constructor without parameters cannot be found.

Why does Java sometimes help Automatic Generation and sometimes does not generate? When you do not define any constructor methods, Java considers that you do not need them. Therefore, an empty one is generated to be called by the new process. When you define the constructor method, java thinks that you know what you are doing, and thinks that you intentionally do not want to include a constructor with parameters, so it won't help you generate them.

Private Constructor

The constructor can be a private method, that is, the modifier can be private. Why do we need a private constructor? There may be several scenarios:

  • You cannot create instances of classes. classes can only be accessed statically, such as Math and Arrays. Their constructor methods are private.
  • Instances that can create a class, but can only be called by static methods of the class. There is a common scenario where only one class object exists, that is, the singleton mode (described later). In this scenario, objects are obtained through static methods, the static method calls the private constructor to create an object. If the object has already been created, the object will be reused.
  • It is only used to be called by multiple other constructor methods to reduce repeated code.

Keyword Summary

Multiple keywords are mentioned in this section. Here we will summarize them:

  • Public: modifies classes, class methods, class variables, instance variables, instance methods, and constructor methods to indicate that they can be accessed externally.
  • Private: you can modify classes, class methods, class variables, instance variables, instance methods, and constructor methods to prevent external access and use only within the class.
  • Static: modifies class variables and class methods. It can also modify internal classes (subsequent sections ).
  • This indicates the current instance. It can be used to call other constructor methods, access instance variables, and access instance methods.
  • Final: modifies class variables and instance variables, indicating that values can only be assigned once. final can also modify instance methods and local variables (for more information, see chapter ).

Class and object Lifecycle

Class

When the program is running, when a class object is created through new for the first time, or directly through the class name callback class variable and class method, Java loads the class into the memory, allocate a space for this type. This space will include the definition of the class, the variables it has, the methods, and other static variables of the class, and assign the initial values to the static variables.

After the class is loaded into the memory, it is generally not released until the program ends. Generally, the class is loaded only once, so there is only one static variable in the memory.

Object

When an object is created through new, the object is generated. In the memory, the instance variable value of this object is stored. Each time a new object is created, an object is generated, there will be an independent instance variable.

In addition to saving the value of instance variables, each object also saves the corresponding class address, so that the object can know its class, access the variables and method code of the class.

The instance method can be understood as a static method, but the parameter this is added. Through the object call method, it can be understood that the static method is called and the object is passed as a parameter to this.

The release of objects is managed by Java's garbage collection mechanism. In most cases, we don't have to worry about it. Objects will be automatically released when they are no longer used.

Specifically, objects and arrays have two memory blocks. The storage address is allocated to the stack, and the actual content is stored in the heap. The memory in the stack is automatically managed. function calls are allocated to the stack and function calls are released from the stack.

The memory in the heap is managed by the garbage collection mechanism. When no Active Variable points to an object, the corresponding heap space may be released. The specific release time is determined by the Java Virtual Machine. The Active Variable, specifically, is the class variable of the loaded class, and all the variables in the stack.

Summary

This section describes classes from the perspective of custom data types, and describes how to define classes, how to create objects, and how to use classes. The custom type consists of class variables, class methods, instance variables, and instance methods. to conveniently assign values to instance variables, this paper introduces the constructor method. This section introduces multiple keywords. We will introduce the meanings of these keywords. Finally, we will introduce the lifecycle of classes and objects.

Implement custom data types through classes, encapsulate the attributes and operations of data of this type, and hide implementation details to a higher level (class and object layers, rather than basic data types and function layers) Consider and operate data, is an important way of thinking for computer programs to solve complex problems.

The Point class introduced in this section has only the basic data type attributes. In the next section, we will introduce the combination of classes to express more complex concepts.

----------------

For more information, see the latest article. Please pay attention to the Public Account "lauma says programming" (scan the QR code below), from entry to advanced, ma and you explore the essence of Java programming and computer technology. Original article, retain all copyrights.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.