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 chapter describes the beauty of Java [from cainiao to masters] series and objects. I hope that through my analysis, readers can better remember relevant knowledge points, master the essence of classes and objects! If you have any questions during reading, contact egg. 1. The class creation and initialization class is usually the abstraction of a class of things. For example, a person is a class, you and I are specific 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, it is embodied in Java classes like the following code: [java] public class Person {String name; int age; void eat () {}} In the object-oriented thinking, all objects are objects. We program them in units of objects. 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: [java] public class Person {String name; int age; public Person (String name, int age) {this. name = name; this. age = age;} void eat () {}} test class: [java] 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, and is allocated on the stack, refers For details about the content allocated to the new stack and the specific JVM memory management, see another blog article: JVM memory management and garbage collection, which provides a detailed introduction. This article is not important here, don't go into depth. 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: [java] public class Person {public Person (int id) {System. out. println ("person (" + id + ")") ;}} 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); public static void main (String [] args) {Build B = new Build () ;}} here I mainly want to explain, use the constructor to create the class and variable initialization sequence, the program output: person (1) person (3) this is build's block! Person (2) Description: No matter where the variable is put, it will be executed before execution of any method, including the constructor. The constructor is a method that must be executed by a class, call without displaying. 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: [java] 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) ;}} output of the program: this is static block! This is non-static block! Person (1) this is non-static block! What are the problems described by person (2? 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: the static keyword. 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: [java] 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 Java reflection mechanism. We will have a special blog post to introduce relevant knowledge points. Let's summarize the object creation process: (including order) according to the output of the following program: [java] 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, initialize static data (declared by static), and perform initialization 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! The person (2) Just verifies our conclusion above. In general, the execution sequence is: static block-> static Attribute-> non-static block-> Attribute-> constructor. Next, we will analyze the attributes and methods of the class. Attributes: attributes in a class are generally classified 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 earlier, 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 be non-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 attribute: 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 behavior of the class, such as: [java] 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: a mechanism between methods with the same method name and different parameter lists in the same class. Different parameter lists are reflected in different types, numbers, and order. Method overloading can be performed if either of them is satisfied. [Java] 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 a method overload, what are the benefits of using such a 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: [java] 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, so it can only handle the Same Name: Error! So it is incorrect to try to reload the method through the return value! Override: 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. [Java] 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, you can rewrite the method function of the parent class: when you need to expand new functions, you do not need to create new methods and supplement them in the parent class methods. This is an embodiment of Object-oriented thinking, this effect can be achieved without rewriting, but rewriting is more in line with the OO idea. There is also a similar concept called "hide": when the sub-class and the parent class method name 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, there is no practical significance. It is equivalent to a new method, but the method name is the same as the parent class, but not the implementation of the parent class method. In Java, variable parameters are called. Sometimes, we cannot determine the number of parameters of a method. We can adopt this mechanism (String... value), the following code: [java] 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: [java] public static String a (String... value) {return "welcome to you:" + value [0];} when there are multiple parameters, the subscript is also used for value: [java] 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. pr Intln (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, we will summarize the relationship between classes and objects: Look at the following code: [java] public class B {public static void main (String [] args) {B B B = new B (); A a = new ();}} in the code of class A {}, both A and B are classes. a and B belong to 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!

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.