Java beauty [from cainiao to master Evolution] and objects (1)

Source: Internet
Author: User

For a pure object-oriented language like Java, classes are the most basic abstract units and I have always hoped to write an article by myself, to better understand your understanding of classes and objects. Today, this wish is coming true! I do not know where to write it, because there are too many things designed in this aspect. When it comes to classes, it is not difficult to think of inheritance, polymorphism, encapsulation, and scope and lifecycle, A lot of things are coming into my mind, so I don't know where to start. This chapterThe beauty of Java [from cainiao to masters] SeriesI hope that through my analysis, readers and friends can better remember relevant knowledge points and master the essence of class and object!

If you have any questions during reading, contact egg:

Mailbox: xtfggef@gmail.com Weibo: http://weibo.com/xtfggef

If there is reprint, please explain the source: http://blog.csdn.net/zhangerqing

I. Create and initialize a class

A class is usually the abstraction of a class of things. For example, a person is a class. You, me, and others are concrete instances of this class, that is, objects. In Java, we can create a class by taking the form of class A {}. We have said that Java is an object-oriented language, and each object should have its own attributes and methods, for example, skin color, height, and so on are attributes of a person. Eating, drinking, and playing are all methods. That is to say, attributes depict the characteristics of classes, and Methods describe the functions of classes, the code shown in the Java class is as follows:

public class Person {String name;int age;void eat(){}}

In the object-oriented thinking, all objects are objects, and we program them in units. Packaging all the attribute methods of this object is encapsulation. Generally, we use the class constructor to create class objects. The constructor is a method with the same name as the class name. We can pass parameters to it for initialization, for example, when we need to initialize the name and age of an object, we can do this:

public class Person {String name;int age;public Person(String name,int age){this.name = name;this.age = age;}void eat(){}}

In the test class:

public class ClassTest {public static void main(String[] args) {Person person = new Person("egg",23);}}

The new operator will open up space for us in the memory. person is the object name and reference. It is allocated on the stack and points to the content allocated by new on the stack. The specific JVM memory is managed, please refer to another blog post: JVM memory management and garbage collection, which has a detailed introduction. It is not important here. Let's analyze this process again: when new person () is called, the compiler first checks whether there is a person () constructor in the original class person, because there is a public person (string name, int age), so the new method is called directly, but in many cases, we do not display the declarative constructor. At this time, when the compiler calls new person, an empty person () constructor without parameters will be automatically added to our person class: Person () {}to execute the class construction process. Speaking of the constructor method, let's take a look at the following code:

public class Person {public Person(int id) {System.out.println("person(" + id + ")");}public static void main(String[] args) {Build b = new Build();}}class Build {Person p1 = new Person(1);public Build() {System.out.println("this is build's block!");Person p2 = new Person(2);}Person p3 = new Person(3);}

Here I mainly want to explain, use the constructor to create the class and the initialization sequence of the variables, the program output:

Person (1)
Person (3)
This is build's block!
Person (2)

Note: No matter where the variable is placed, It will be executed before any method is executed, including the constructor. The constructor is a method that must be executed by a class and does not need to be shown for calling. At the same time, no matter where the variables are distributed, as long as they are outside the method, they must be initialized before the method. Speaking of this, we have to talk about another key knowledge point static block and non-static block. Both of them have a very simple declaration method. You only need a pair of braces {}. For static blocks, add the static keyword in front. Let's write a small program to see it:

Public class person {/* Static block */static {system. Out. println ("this is static block! ");}/* Non-static block */{system. Out. println (" this is non-static block! ");} Public person (int id) {system. out. println ("person (" + ID + ")");} public static void main (string [] ARGs) {person p1 = new person (1 ); person P2 = new person (2 );}}

Program output:

This is static block!
This is non-static block!
Person (1)
This is non-static block!
Person (2)

What are the issues? Observe: we have two new objects, but the static block is executed only once, instead of the static block, and both objects are executed before the constructor is called. We seem to have come to some conclusions: static blocks are executed during class loading (after the. Class file is loaded) and are executed only once. Non-static blocks are executed before the constructor is called. Each time an instance object is generated, a non-static block is called. Here, I want to introduce a very important knowledge point:StaticKeyword. Generally, variables, methods, or blocks declared as static belong to class variables, class methods, and class attributes (memory allocation in the method area ). Like static blocks, other static data also has this feature: initialization is only executed once during class loading. Another important feature of class variables and class methods is that external objects can be referenced directly by class names, as shown in the following code:

public class Person {static int id = 10;}class Test{public static void main(String[] args) {System.out.println(Person.id);}}

Apart from using the new operator, we also have some other methods to create classes, such as the reflection mechanism of Java. We will have a special blog post to introduce relevant knowledge points.

Let's summarize the object creation process: (including the order) according to the output of the following program:

Public class person {public person (int id) {system. out. println ("person (" + ID + ")") ;}} class build {/* Static block */static {system. out. println ("this is static block! ");}/* Non-static block */{system. Out. println (" this is non-static block! ");} Person p1 = new person (1); // ------------ 1 ----------- public build () {system. Out. println (" this is build's block! "); Person P2 = new person (2);} person P3 = new person (3); public static void main (string [] ARGs) {build B = new build ();}}

This is static block!
This is non-static block!
Person (1)
Person (3)
This is build's block!
Person (2)

1. First load the. Class file, create a class object, and initialize static data (declared by static) only once.

2. New build () allocates space on the stack.

3. Execute non-static blocks.

4. Execute initialization of all variables defined outside the method.

5. Execute the constructor.

Let's take a look at the example: Put static before the annotation line in the above example, the output will change:

This is static block!
Person (1)
This is non-static block!
Person (3)
This is build's block!
Person (2)

The execution sequence is static block, static Attribute-> non-static block, attribute-> constructor. Next, we will analyze the attributes and methods of the class.

Supplement: NetizensA52360509Correction: for static or non-static blocks and attributes, the initialization order is determined by their order in the code.

Attribute:

Attributes in a class are generally divided into class attributes (global variables), instance attributes (global variables), and local attributes (local variables ). <This is my score. Although some people do not score this score, it doesn't matter. It is the most important to understand them>.

Class attributes:As mentioned above, the attributes declared as static are initialized only once throughout the process, and only one space is opened in the memory. The values are consistent wherever called. Once modified, all the places that reference it will be modified. Generally, it is called directly by class name.

Instance attributes:Instance variables can not be initialized. For example, if an instance variable of an integer type is not initialized, the default value is 0. If the initial value is not assigned to a local variable, however, the program reports an error when using this variable. The instance variables allocate memory space in the heap and stack. The object is allocated in the heap, And the stack references the object.

Local attributes:A local variable is a variable declared within the method. The life cycle is only within the method, and the variable disappears after the method ends. The local variable must be initialized and used. Otherwise, an error is reported, that is, if you define a local variable in the method without assigning a value, you must assign a value when using this variable. Otherwise, an error is returned. At the same time, local variables can block global variables.

Method:

The method is the action of the class, such:

public void say(){dosomething;...}

It consists of the method header and method body. The method header includes the access control operator (such as public private) and return type (the return type determines the type of the result generated by the method after the call) method Name and parameter list. The method declared as void. The return value is null. In special cases, we can add some special keywords for the method to implement special functions, such as synchronized, final, static, and abstract. In terms of methods, I only want to introduce two important aspects: overload and overwrite ).

Overload:

InSame classA mechanism between methods with the same method name and different parameter lists. Different parameter lists are reflected in different types, numbers, and order. Method overloading can be performed if either of them is satisfied.

Public class areacal {/* calculate the rectangular area */Public int area (INT width, int height) {return width * height ;} /* calculate the square area */Public int area (INT edge) {return edge * edge;}/* calculate the area of the circle */Public double area (float radius) {return 3.14 * radius ;}}

As shown in the example, if the same method name is "area", different parameters are synchronously input to implement different functions. This is the method overload. What are the advantages of using this mechanism? In my personal sense, it is a unified model. To call the same method with the same function, we only need to input different parameters to enhance the readability and ease of maintenance of the program, when there are many methods with similar functions, it would be bad if we design a name for each method and want to distinguish them by name, it also makes people think that the program is not readable, and the design is not clever enough! Here the question is: can we identify the method overload through the return value of the method? Let's take an example:

public int area(int width, int height) {return width * height;}public float area(int width, int height){return width * height;}

When the two methods are called in other environments, their return values are not obtained first. The return values are returned only after the method is executed. At the beginning of the call, the compiler cannot determine their differences, therefore, an error is returned only when the same name is used! So it is incorrect to try to reload the method through the return value!

Rewrite:

Override exists in inheritance. In two classes (the relationship between the subclass and the parent class), The subclass overrides the parent class method with the same method name, A mechanism with the same parameters.

public class B extends A {public String a(String name) {return "welcome to you :" + name;}}class A {public String a(String name){return "hello:"+name;}}

When the subclass inherits the parent class and wants to extend the method functions of the parent class, you can use the rewrite function. The purpose is to: When you need to expand new functions, you do not need to create a new method and add it to the parent class method. This is an embodiment of Object-oriented thinking, which can be achieved without rewriting, however, rewriting is more in line with the OO idea. There is also a similar concept calledHide: When the sub-class and the parent class method names are the same and the parameters are different, the sub-class hides the implementation of the parent class method. This is a mechanism, a method called, and has no practical significance, it is equivalent to creating a method, but the method name is the same as the parent class, but not the implementation of the parent class method.
Variable Parameter calls in Java

Sometimes, we cannot determine the number of parameters of the method. We can adopt this mechanism (string... value), as shown in the following code:

public class B{public static String a(String ... value) {return "welcome to you :" + value;}public static void main(String[] args) {System.out.println(a("egg"));}}

The printed result is: Welcome to you: [ljava. Lang. String; @ 61de33. This part of information is the array information, so we continue to study and find that when you write the parameter string... the value format is already equivalent to: String [] value by default. Therefore, you need to write the data obtained inside the method as an array submark:

public static String a(String ... value) {return "welcome to you :" + value[0];}

When there are multiple parameters, the subscript is also used for the value:

public class B {public static String a(String... value) {return "welcome to you :" + value[0] + value[1] + value[2];}public static void main(String[] args) {System.out.println(a("egg", ":niu", ":baby!"));}}

This mechanism is particularly useful in some development, reducing the amount of code and making the program more concise, but sometimes it sacrifices a little readability.

Ii. Relationship between classes and objects

After so many drills above, let's summarize the relationship between classes and objects: Look at the following code:

public class B {public static void main(String[] args) {B b = new B();A a = new A();}}class A {}

In this Code, both A and B are classes. A and B are objects. What is the relationship between them?

1. A class is a general term for a class of things with the same attributes. It is an abstraction.

2. objects are specific manifestations of classes, also known as instances.

3. A class is a static concept, while an object is a dynamic mechanism.

Everyone has different opinions. What is the relationship between them? I hope you can add this question. I sincerely hope that you can think carefully and make valuable suggestions! Many readers have suggested that the previous blog post is too long. I hope it can be written as short as possible to facilitate reading. So I put other content in the next article and hope my friends can continue reading it!

This chapter is complete.

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.