Java object-oriented explanation

#############Java object-oriented explanation ################# 1. Basic object-oriented concepts 2. Classes and objects 3. Definition format of classes and objects 4. Object and memory analysis 5. Encapsulation 6. Construction method 7. This keyword 8. Value transfer and reference transfer? 9. One to one relationship 10, static keyword 11, main method analysis 12, inheritance 13, inheritance 13, inheritance 13, initialization of objects 14, initialization of objects 14, rewrite of methods 15, rewrite of methods 15, superkeyword 16, final keyword 16, final keyword 17, superkeyword 16, super keyword 16, final keyword 17, abstract class 18, interface 19, interface 19, polymorphism 20, polymorphism 20, instancepof keyword 21, one-to-one relationship 10, one-to-one relationship 10, one-to-one relationship of objects 10, static keyword 11, main method analysis 12, analysis 12, inheritance 12, 12, inheritance 13, inheritance 13, inheritance 13, initialization of objects 14, initialization of objects 14, rewrit15 of method rewrit15, super keyword 15, super keyword 16, final keyword 17, abstraction 18, interface 18, interface 19, polymorphism 19, polymorphism 20, instance of 20, instanceof 21 for keyword 21, internal keyword 21, inner class \\\\\\#\interface19 19################### 1 The essence of the basic concept of object-oriented is the abstract thinking process and object-oriented method embodied in the establishment of model (Baidu Encyclopedia). It is not only a programming thinking, but also a way of thinking

How to establish object-oriented thinking? 1. First the whole, then the part. 2. First abstract, then concrete. 3. What can be done and how to do it

2. Class and object class: class is a kind of classification, a category and a template. It describes the behavior and state of a class of objects. It is a collection of things with the same characteristics (attributes) and behavior (Methods). Object: it is the product of a personality, the characteristics of an individual, and an instance of a class, with state and behavior

3. Class and object definition format class definition: class name {property name; return value type method name () {}}

Object definition: if a class wants to operate, it must rely on the object. The object definition format is as follows: class name object name = new class name ();

If you want to access properties or methods (method definitions) in a class, you can rely on the following syntax: access properties in a class: object. Property; call methods in a class: object. Method ();

In Java, object declaration has two meanings: Horse = null// Indicates that an object is declared but cannot be used. There is no specific memory point to the instantiated object: Horse = new horse()// Indicates that an object has been instantiated. You can use

horse. eat(); // Call the method new horse() through an object eat();// Anonymous object calling method

4. Object and memory analysis

New keyword means to create an object. New keyword means to instantiate an object. New keyword means to apply for memory space. Note: if you use an object that does not apply for memory space, a null pointer exception will be reported: Java lang.NullPointerException

(1) New keyword: it means to apply for space from memory. It also means to instantiate an object and create an object. (2) the size of an object in memory and the sum of the memory size occupied by all the attributes of the object. Reference type variables account for 4 bytes on 32-bit systems and 8 bytes on 64 bit systems. Plus the size of implicit data of external objects. (3) Only the same type can be assigned values. (4) different references point to the same object. If any reference changes the value of the object, other references will be reflected. (5) problems to pay attention to in programming. When determining not to use the object, release the object as soon as possible: Reference = null (6) When an object in the heap is not pointed to by any reference variable, the object will be considered as a garbage object by the GC program of the JVM and will be recycled

5. Encapsulation the concept of encapsulation encapsulation is one of the three characteristics of object-oriented thinking. Encapsulation is to hide the implementation details and only provide external access interfaces. The method of packaging and hiding details. Encapsulation includes: attribute encapsulation, method encapsulation, class encapsulation, component encapsulation, modular encapsulation, system level encapsulation... Advantages of encapsulation: modularity, information hiding, code reuse, plug-in, easy debugging, security encapsulation disadvantages: it will affect the execution efficiency

Before encapsulation: all attributes can be accessed and modified directly. Class person {string name; int age;}

After encapsulation: class person {/ / the attribute is a member variable, which is privatized so that other objects cannot directly access the attribute private string name; private int age; / / the variables defined in the parameters and methods are local variables public void setname (string name) {this. Name = name;}   public String getName(){   return name;} }

Differences between member variables and local variables A. different positions in the class. Member variables: local variables defined in the class: parameters defined in the method or method B. different positions in memory. Member variables: in heap memory (member variables belong to objects and objects go into heap memory) local variables: in stack memory (local variables belong to methods and methods go into stack memory) C Different member variables in the life cycle: exist with the creation of the object and disappear with the destruction of the object. Local variables: exist with the call of the method and disappear with the completion of the call of the method. D. different initialization values. Member variables: have default initialization values, and the reference type is null by default. Local variables: there is no default initialization value, which must be defined and assigned, Note: local variable names can be the same as member variable names. When using methods, the proximity principle is adopted.

6. Construction method parameterless construction method: public dog() {} / / if a class does not define a construction method, it defaults to parameterless construction. If a parameterless construction method is defined, it is better to display the definition of a parameterless construction method

Construction method with parameters: public dog (string name) {this. Name = name;}

Multi parameter construction method: public dog (string name, int age) {this. Name = name; this. Age = age;}

(1) The constructor name is the same as the class name, and there is no return value declaration (including void) (2) the constructor is used to initialize data (properties) (3) there will be a default parameterless constructor in each class (4) if there is a displayed constructor in the class, the default constructor will be invalid (5) if there is a construction method to display, we also want to keep the default constructor method, which needs to be written out. (6) the construction method can have many, but the parameters are different. It is called the overload of the construction method (7) calling another construction method in the construction method, using this (...). The sentence code must be in the first sentence. (8) There must be an exit for calls between constructor methods. (9) constructor methods or setter methods can be used to initialize data for objects, and both methods are usually retained. (10) a good programming habit is to retain the default constructor method. (in order to facilitate some frame code to create objects using reflection) (11) private dog() {}, The construction method is privatized. When our requirement is to ensure that there is only one object in this class (the singleton pattern is the privatized constructor).

7. This keyword this keyword refers to the property in the reference calling class of the current object: this Attribute name refers to the member variable in the access class, which is used to distinguish the member variable from the local variable (duplicate name problem). Call the method in the class: this. Method name, which is used to access the member method of the class, and call the class construction method: this(); To access the constructor of this class, you can have parameters in (). If there are parameters, you will call the specified parameterized constructor. Note: 1 This() cannot be used in ordinary methods, but can only be written in constructor 2 Must be the first statement in the constructor

8. Value passing and reference passing?

First of all, note: in Java, there is only passing by value, not by reference. Java data types can be divided into two categories: primitive types and reference types

a. Pass by value of basic data type

The main function calls the swap function to exchange the values of X and Y. however, after calling the function, it is found that the values of X and Y in main are not exchanged. Including a method that can exchange two variables is not found in the Java API. This is related to the characteristics of the Java language. Through a diagram, you can know the running results of the above program.

The X, y in the X, y and swap functions of main function are stored in different regions. When the swap function is called in main, the value of X and Y in main will be assigned to the main in the main. When x and y are exchanged in the swap function, only x and Y in the swap frame are exchanged, and X and Y in main will not be changed. So when the function returns, X and Y in main do not change

b. Reference data types are passed by value. There are three types of reference data types: ① interface ② class ③ array

After running the program, I found that the operation of swap function on a [0] and a [1] actually affected the values of a [0] and a [1] in the main function. It's incredible. Why did this happen. The original reference type is passed by value, and the address of the object is passed

It can be seen from the figure that in swap, only the address of the array is obtained, and the elements of the array are not copied. The operation on the array in swap is a direct operation on the array in the main function. Therefore, after the swap function returns, the values of a [0] and a [1] in the main function are exchanged

quote: https://blog.csdn.net/u013309870/article/details/75499175

9. One to one relationship of objects

There are many kinds of object correspondence in Java, such as one-way one-to-one, two-way one-to-one, one to many, many to one, many to many, etc. their implementation principles are the same. In fact, they can be understood as the combination of classes. The object is operated as another attribute to produce correspondence (many design patterns are realized through the combination of classes)

quote: https://blog.csdn.net/IT_arookie/article/details/83350946

10、 Static keyword static keyword is used to facilitate calling without creating an object (method / variable). A. use the static keyword to modify an attribute: variables declared as static are essentially global variables. B. use the static keyword to modify a method: define a method in a class as static, that is, you can call this method (class call) without the object of this class. C. use the static keyword to modify a class (inner class): methods declared as static have the following restrictions: they can only call other static methods, and vice versa. They can only access static data. They cannot reference this or super in any way. They are not allowed to modify local variables

Refer to: https://www.cnblogs.com/dolphin0520/p/3799052.html

11. Main method analysis main method: public static void main (string [] args) {/ / code block}

Public: public, maximum access permission static: static, no need to create an object void:: indicates no return value, no need to return results to the JVM Main: method name, fixed method name string [] args: indicates that the parameter is a string array, which can be passed in when calling the method

12. Inheritance is one of the three characteristics of object-oriented. Inheritance is the technology of using the existing class definition as the basis to establish a new class. The new class definition can add new data or new functions, or use the functions of the parent class, but it can not selectively inherit the parent class

The inherited class is called the parent class (superclass), and the class that inherits the parent class is called the child class (derived class) code reuse can be realized through inheritance. Subclasses have non private properties and methods of the parent class. Subclasses can have their own properties and methods, that is, subclasses can extend the parent class. Subclasses can implement the methods of the parent class in their own way. For constructors, they can only be called, not inherited, and can be called by using super(), For inheritance, the subclass will call the constructor of the parent class by default, but if there is no default parent class constructor, the subclass must display the constructor of the specified parent class (through super ()), and must be the first thing to do in the subclass constructor (the first line of code). For protected, it indicates that the class user is private, but for any subclass that inherits from this class or any other class in the same package, it can be accessed. Java inheritance is single inheritance, but multiple inheritance is allowed,

Syntax: [access rights] class subclass name extends parent class name {class body definition;}

Example: public class dog {private string name; private string sex; public void eat() {system. Out. Println ("eat");}} Public class homedog extensions dog {/ / class definition} public class huskydog extensions dog {/ / class definition}

Protected (protected access modifier, used to modify properties and methods. Properties and methods modified with protected can be inherited by subclasses)

(1) Inheritance occurs between multiple classes (2) inheritance uses the keyword extends (3) Java can only inherit single, allowing multi-level inheritance (4) the inherited class is called the parent class (super class), and the class that inherits the parent class is called the child class (derived class) (5) non private properties and methods in the parent class can be inherited by the child class (6) protected (protected access modifier), the modified property or method can be inherited by subclasses (7) the constructor cannot be inherited (8) when creating an object, the constructor will be called. Calling the constructor does not necessarily mean creating an object (9) When instantiating a subclass object, the constructor of the parent class will be called first. If there is no default constructor in the parent class, the subclass must be displayed through super (...) To call the parameter constructor of the parent class, super can only be in the first sentence of the subclass constructor

The advantages of inheritance: A. improve the reusability of code B. improve the maintainability of code C. making the relationship between classes is the premise of polymorphism. The disadvantages of inheritance: enhance the coupling between classes

13. Object initialization

By executing each code block or constructor, output the value of the field after the execution of the previous code block, so as to explore the initialization order of the object. From the current output results, we can draw the following conclusions about the initialization order of objects: 1 Parent class static field initialization 2 Parent static code block and subclass static field initialization (next explore the order of the two) 3. Subclass static code block 4. Parent common field initialization 5. Parent construction code block 6. Parent constructor 7. Subclass common field initialization 8. Subclass construction code block 9. Subclass constructor

When initializing the child static field childstr, we assign the value of the parent static field fatherstr. It can be seen from the output result that the initialized value of childstr is the value given to fatherstr after the execution of the static code block of the parent class. It can be seen that the execution order of the two is: parent static code block = = > child static field initialization

Initialization sequence (final result):

Parent class static field initialization parent class static code block subclass static field initialization subclass static code block parent class common field initialization parent class construction code block parent class constructor subclass common field initialization subclass construction code block subclass constructor

quote: https://www.jb51.net/article/111157.htm

14. Method overriding method in Java, subclasses can inherit the methods in the parent class without rewriting the same methods. However, sometimes subclasses do not want to inherit the methods of the parent class intact, but want to make certain modifications, which requires method rewriting. Method overrides are also called method overrides. In subclasses and parent classes, after overriding a method, whose method will be called depends on the object type created.

Rewriting characteristics: A. it occurs in the child parent class, and the two method return values, method names The parameter list must be completely consistent (the subclass overrides the method of the parent class) B. the exception thrown by the subclass cannot exceed the exception thrown by the corresponding method of the parent class (the subclass exception cannot be greater than the parent class exception) C. the access level of the subclass method cannot be lower than the access level of the corresponding method of the parent class (the subclass access level cannot be lower than the parent class access level) d. if the method in the parent class uses private Static and final can be modified by any modifier, so they cannot be overridden by subclasses.

Interview question: what is the difference between overloading and overriding?

15. Super keyword can be understood as a reference to the parent class. Using super to call the properties, methods, and construction methods of the parent class can complete the following operations: A. using super to call the properties in the parent class can obtain information from the parent class instance. b. Using super to call the method in the parent class, you can delegate the parent object to help complete something. c. When super is used to call the constructor in the parent class (in the form of super (argument)), the corresponding constructor in the parent class must be called in the first statement of the subclass constructor. If it is not displayed, the parameterless constructor of the parent class will be called by default, such as super();

16. Final keyword use the final keyword to complete the following operations: A. use the final keyword to declare a constant. When final modifies a basic data type, it means that the value of the basic data type cannot be changed after initialization; If final modifies a reference type, it can no longer point to other objects after initialization, but the content of the object pointed to by the reference can change. B. use the final keyword to declare a method, which is the final method and can only be inherited by subclasses, but cannot be overridden by subclasses. c. Use the final keyword to declare a class, which will be transformed into the final class. For a class without subclasses, the class modified by fianl cannot be inherited. d. Use final in the method parameter. The value of the parameter cannot be modified inside the method (explained in detail in the internal class)

When the final variable is of basic data type and string type, if its exact value can be known during compilation, the compiler will use it as a compilation time constant. However, it should be noted that the compiler will carry out such optimization only when the final variable value can be known exactly during compilation. After the reference variable is modified by final, although it can no longer point to other objects, But the content of the object it points to is variable.

Refer to: https://www.cnblogs.com/xiaoxi/p/6392154.html

17. Abstract class the basic concept of abstract class (1) many objects with the same characteristics and behavior can be abstracted as a class; many classes with the same characteristics and behavior can be abstracted as an abstract class. (2) classes declared with abstract keyword are abstract classes

Define an abstract class

abstract class Animal{   public abstract void move(); } Abstract class person extends animal {private string name; / /... Public abstract void eat(); / / abstract method}

Rules for abstract classes: A. abstract classes can have no abstract methods, and classes with abstract methods must be abstract classes. B. non abstract classes inherit abstract classes, and abstract classes must implement all abstract methods. C. abstract classes can inherit abstract classes, and can not implement parent class abstract methods. d. Abstract classes can have method implementations and attributes e, abstract classes cannot be instantiated F, abstract classes cannot be declared final g, and abstract classes can have construction methods

18. Interface definition format: interface interface name {global constant; abstract method;} List: interface Ieat {/ / public abstract void eat(); void eat(); / / default is public abstract void eat(); / / public static final int num = 10; int num = 10;}

interface ISleep extends IEat{ void sleep(); } Rules for using interfaces: (1) define an interface and use the interface keyword; (2) in an interface, only constants and abstract methods can be defined. After JDK1.8, the default implementation method can be defined; (3) the interface can inherit multiple interfaces: Extensions XXX, XXX (4) a specific class implements the interface and uses the implements keyword (5) a class can implement multiple interfaces (6) Abstract classes can implement interfaces without implementing interface methods. (7) the methods defined in the interface do not declare access modifiers. The default is public. (8) interfaces cannot have construction methods. (9) interfaces cannot be instantiated. (1) java8 adds default methods and static methods. These two methods can have method bodies (2) The default method belongs to the instance, and the static method belongs to the class (Interface) (3) the static methods in the interface will not be inherited, and the static variables in the interface will be inherited

public interface IUser {   static void say() {   System.out.println("say_" + IUser. class);  }   default void eat() {   System.out.println("eat_" + IUser. class);  } }

19. Polymorphism refers to the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable. It is not determined during programming, but only during the running of the program, that is, a reference variable will point to the instance object of which class, and the method call issued by the reference variable is the method implemented in which class, It can only be determined during the running of the program. Because the specific class is determined only when the program is running, so that the reference variable can be bound to various class implementations without modifying the source program code, resulting in the change of the specific method called by the reference, that is, the specific code bound when the program is running can be changed without modifying the program code, so that the program can select multiple running states, which is polymorphism

Polymorphism can be roughly divided into two categories: (1) method overloading and rewriting (2) object polymorphism

//Use the reference of the parent class to point to the child class object (use the large type to accept the small type, and transform upward and automatically) chicken home = new homechicken();

When programming, writing code for abstract types is called abstract oriented programming (or interface oriented programming). Parent classes are usually defined as abstract classes and interfaces

Object polymorphism: object polymorphism comes from multiple classes in the inheritance relationship, and the upward Transformation: convert the child class instance to the parent class reference format: parent class, parent class object = child class instance;  automatic conversion takes the basic data type operation as an example: int i = 'a'; (because the capacity of char is smaller than int, it can be completed automatically)

Downward Transformation: convert a parent instance to a subclass instance. Format: subclass subclass object = (subclass) parent instance; cast basic data type operation as an example: char c = (char) 97; Because the integer is 4 bytes larger than the char 2 bytes, it needs to be forced to complete A. method overloading and rewriting is the expression of method polymorphism B. multiple subclasses are multiple forms in the parent class C. parent class references can point to child objects and automatically convert D The subclass object points to the parent class reference and needs to be forcibly converted (Note: exceptions will be reported if the type is wrong) e. try to use the parent class reference in actual development (which is more conducive to expansion)

Due to the upward transformation, the parent class reference pointing to the child class can only access the methods and properties owned by the parent class. For the methods existing in the child class but not in the parent class, the reference cannot be used, although the method is overloaded. If the subclass overrides some methods in the parent class, these methods defined in the subclass must be used when calling these methods (dynamic connection and dynamic call). For example: class a {void fun1() {} void fun2() {}}

Class B extensions a {void fun1 (string a) {} / / overload fun1 void fun2() {} / / rewrite fun2}

Class C {public static void main (string [] args) {a a = new b(); a.fun1(); / / the fun1 method of class a will be called here. Due to the upward transformation, B's fun1 (string a) will be discarded a.fun2(); / / the fun2 method of B will be called here. Because it is the object of new B and B rewrites fun2, B's fun2}}

For object-oriented, polymorphism can be divided into compile time polymorphism and run-time polymorphism. Editing time polymorphism is static, which mainly refers to method overloading, while runtime polymorphism is dynamic, which is realized through dynamic binding, that is, what we call polymorphism

There are three necessary conditions for Java polymorphism: inheritance, rewriting and upward transformation. Inheritance: there must be subclasses and parent classes with inheritance relationship in polymorphism. Override: a subclass redefines some methods in the parent class. When these methods are called, the subclass's methods will be called. Upward Transformation: in polymorphism, you need to assign the reference of the subclass to the parent object. Only in this way can the reference have the skills to call the methods of the parent class and the subclass

Polymorphic inheritance based on inheritance implementation is reflected by rewriting several different subclasses of the same method of the parent class. For the parent class type that references a subclass, when processing the reference, it is applicable to all subclasses that inherit the parent class. Different subclass objects have different implementation of methods and different behaviors generated by executing the same action.

The polymorphic reference to the interface based on the interface implementation must be an instance program that specifies a class that implements the interface. At run time, the corresponding method is executed according to the actual type of the object reference.

Refer to: https://www.cnblogs.com/chenssy/p/3372798.html

20. Instanceof keyword instanceof is used to check whether an object is of the specified type. It is usually used when casting a parent class reference to a child class reference to avoid a type conversion exception (ClassCastException).

The syntax format is as follows: object instanceof type - return Boolean type value

Example: if (homechicken instance of chicken) {/ /...} This statement is generally used to judge whether an object is an instance of a class. It returns true or false. The design principle of the parent class. Through the instanceof keyword, we can easily check the type of the object. However, if there are too many subclasses of a parent class, this judgment is cumbersome. So how to design a parent class? a. The parent class is usually designed as an abstract class or interface, in which the interface is given priority. If the interface cannot be satisfied, the abstract class is considered.

b. A concrete class does not inherit from another concrete class as much as possible. The advantage is that there is no need to check whether the object is an object of the parent class.

21. Inner class an inner class is a class defined inside a class. Member internal class: the internal class object depends on the external class object, that is, when creating a common internal class object, you first need to create its external class object. The internal class object can access all the access permission fields in the external class object. At the same time, External class objects can also access the field members of all access permissions defined in the internal class through the object reference of the internal class. The internal class format is as follows: class outer {class inner {}} compiling the above code will produce two files: outer Class and outer $inner class。

Create an internal class object externally. An internal class can not only generate instantiated objects in the external class, but also be instantiated outside the external class. Then, the *. Generated from the internal class Class file: outer $inner The class "$" symbol will be replaced with "." Therefore, the access of internal classes is expressed in the form of "external class. Internal class".

Outer out = new Outer() ;// Generate an external class instance outer Inner in = null; // Declare inner class object in = out new Inner() ; // Instantiate internal class object

A local inner class can be used as a member of a class, You can also define classes within methods (not commonly used, anonymous inner classes can display the functions of local inner classes). In local inner classes, you can access all access permission fields of external class objects, while external classes cannot access the fields defined in local inner classes. Note: A. local inner classes can only be instantiated in the method that defines the inner class, and cannot be instantiated outside this method. B. local inner classes An internal class object cannot use a non final local variable of the method in which the internal class is located. class Outer {   public void doSomething(){   class Inner{     public void seeOuter(){}   }   } }

Static inner class defines a static inner class inside a class: static means that the inner class can access it like other static members when there is no external class object. Static nested classes can only access static members and methods of external classes. Non static member class outer {static class inner {}}} class test {public static void main (string [] args) {outer.inner n = new outer. Inner();}}

Anonymous inner class an anonymous inner class is an inner class without a name. There are three cases of anonymous inner classes: (1) inherited anonymous inner classes (2) interface anonymous inner classes (3) parametric anonymous inner classes

When using anonymous inner classes, Remember the following principles: (1) there can be no constructor, only one instance. (2) no static member or static method can be defined. (3) it cannot be public, protected, private or static. (4) it must be behind new, which implicitly implements an interface or inherits a class. (5) Anonymous inner classes are local, so all restrictions on local inner classes apply to them

Local internal classes accessing local variables must be decorated with final. Why? When calling this method, if the local variable is not decorated with final, its life cycle is the same as that of the method. When the method is called, it will be put into the stack. After the method ends, it will pop up and the local variable will disappear. If the local internal class object does not disappear immediately, it is obviously impossible to use this local variable, If the final modification is used, it will enter the constant pool when the class is loaded. Even if the method bounces the stack and the constant of the constant pool is still there, it can continue to be used.

Note: in jdk1 8 cancels the use of final decoration that must be displayed for variables used in local internal classes. The compiler will add final to this variable by default

The role of internal classes. Each internal class can independently inherit from an implementation (Interface), so whether the external class has inherited a The implementation of (Interface) has no impact on the internal class. Without the ability provided by the internal class to inherit multiple concrete or abstract classes, some design and programming problems are difficult to solve. From this point of view, the internal class makes the solution of multiple inheritance complete. The interface solves some problems, and the internal class effectively implements "multiple inheritance".

Dependent on external class objects: member internal class, method internal class, anonymous internal class, static internal class does not depend on external class objects. Therefore, we give priority to selecting static internal classes in the project (no memory leakage)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>