Java basics-java object-oriented programming 2

Source: Internet
Author: User
Tags abstract constant constructor define abstract function definition inheritance modifier modifiers

01. Object-oriented (static keyword)

Usage: it is a modifier used to modify members (member variables and member functions ).
When a member is statically modified, an additional call method is provided. In addition to being called by an object, the member can also be called directly by the class name. Class name. Static member.
Object-specific content along with object storage can be defined as static content and placed in the shared area.
The method area, shared area, and data area in the class are all in the same zone.

Static features:
(1) loading with the class disappears as the class disappears. That is to say, the static state disappears with the disappearance of the class, indicating that its life cycle is the longest.
(2) takes precedence over object existence. It is clear that static exists first and object exists later.
(3) shared by all objects;
(4) it can be called directly by the class name.
Differences between instance variables and class variables:
(1) storage location: class variables exist in the method zone as the class is loaded; instance variables exist in the heap memory as the object is established.
(2) life cycle: the maximum life cycle of a class variable disappears with the disappearance of the class; the life cycle of an instance variable disappears with the disappearance of the object.
Static usage considerations:
(1) Static methods can only access static members and static methods. Because static methods and variables are present during class loading, non-static variables exist only when the object exists.
(2) Non-static methods can access static or non-static methods.
(3) this and super keywords cannot be defined in static methods. Because the static method takes precedence over the object, this cannot appear in the static method.
(4) The main function is static.
Static has the following advantages:
Benefits: the shared data of objects is stored in separate space to save space memory. It is not necessary to store a copy of each object; it can be called directly by class name.
Disadvantage: the lifecycle is too long, and access is limited. Static access is only allowed although static access is good.

02. Object-oriented (main function)

Main function: a special function that can be called by jvm as the program entry.
Main function definition:
Public: indicates that the function has the highest access permission.
Static: indicates that the main function already exists as the class is loaded.
Void: the main function does not return a specific value.
Main: not a keyword, but a special word, which can be recognized by jvm.
Function parameters (String [] args): the parameter type is an array. The elements in this array are strings and String arrays.

When jvm calls the main function, it imports new String [0];
Start the jav VM and pass the parameter java TestMain haha heiehi to the main function.
This indicates that the Java virtual machine passed the haha and parameters to the main function when executing TestMain.
You can also use the following method:

The code is as follows: Copy code
Class MainDemo
{
Public static void mian (String [] args)
 {
String [] arr = {"1", "2", "3 "};
Maintest (arr );
 }
}
Class Maintest
{
Public static void main (String [] args)
 {
For (int I = 0; I <args. length; I ++)
  {
System. out. println (args [I]);
  }
 }
}

03. Object-oriented (when to use static resources)

We need to start from two aspects:
Because the static modification content is member variables and functions.
When do I define static variables (class variables?
When shared data exists in the object, the data is modified statically. The Special Data of the object must be defined as non-static and stored in the heap memory.

When do I define static functions?

When the function does not access non-static data (object-specific data), the function can be defined as static.

04. Object-oriented (Static Application-tool class)

Each application has common functions that can be extracted and encapsulated.
If you want to make the program more rigorous, if you do not need an object, you can set the members of a class to static and directly call it by class name.
After static methods are used, it is convenient to use them. However, this class can still be used by other programs to create objects. To be more rigorous, we should force the class to not create objects, you can privatize constructors so that object creation is not allowed.

05. Object-oriented (help document creation)

Java instructions are annotated in the document.
Format:
/**
Description
@ Author
@ Version
@ Param parameter
@ Return value
*/
Each class and all member functions modified with public should be annotated with instructions in the document.

Generate a document for a class:
Javadoc-d Directory (path)-author-version
Generate a document for a class, which must be public

By default, a constructor with an empty parameter is created for a class. The default constructor has the same permissions as the class.
If it is modified by public, the default constructor also carries the public modifier.
If the class is not public, the default constructor does not have a public modifier.
The permissions of the default constructor change with the change of the class.

06. Object-oriented (static code block)

Static
{
Statement for executing static code blocks;
}

Feature: it is executed only once when the class is loaded. The static code block before the main function takes precedence over the main function execution.

When a class is a new object, the construction code block and static code block in the class are executed in the following sequence: Static code block, construction code block, and construction function.

Static code blocks are loaded with classes and can only call static members.

07. Object-oriented (object initialization process)

Load the "class. class" file, execute static code blocks (not executed), construct code block initialization, and initialize the constructor;
Person p = new Person ("zhang san", 20 );
What this sentence does:
1. Because new uses Person. class, the Person. class file is first found and loaded into the memory.
2. Execute the static code block in this class. If yes, initialize the Person. class.
3. Open up space in heap memory and allocate the memory address.
4. Create a special attribute of the object in the heap memory and perform Default initialization.

5. Initialize the display of attributes.
6. Initialize the construction code block of the object.
7. Initialize the corresponding constructor for the object.
8. Assign the memory address to the variables in the stack memory.

08. Object-oriented (object call Member process)

09. Object-oriented (Singleton design mode)

Design Pattern: There are 23 design patterns in java.
The most effective method to solve a certain type of problem.
Singleton design mode: only one object exists in the memory of a class.
To ensure that the object is unique:
(1) in order to prevent other programs from creating such objects too much, other programs are prohibited from creating such objects first.
(2) to allow other programs to access this type of object, we have to customize an object in this class.
(3) to facilitate access to custom objects by other programs, some access methods can be provided externally.
How are these three components reflected:
(1) privatize constructors
(2) create a class object in the class,
(3) provides a method to obtain the class object.

The code is as follows: Copy code
Class Single
{
Private Single (){}
Private static Single s = new Single ();
Public Static Single getInstance ()
 {
Return s;
 }
}

Outside the class, use Single s = Single. getInstance (); to access.

How to describe things and how to describe things.
You only need to save the object of this transaction in the memory for the moment, as long as three steps are added.

10. Object-oriented (Singleton design mode 2)

The second method of Singleton design mode:

The code is as follows: Copy code
Class Single
{
Private static Single s = null;
Private Single (){}
Public static synchronized Single getInstance ()
 {
If (s = null)
S = new Single ();
Return s;
 }
}

The first mode is to initialize the object first, which is called the hungry Chinese style.
Feature: The Single class has already created an object as soon as it enters the memory. If you are hungry, do it.
Development is usually conducted in the hungry Chinese style.
The second method is called before initialization.
Feature: The Single class is in memory, and the object does not exist. The object is created only when the getInstance () method is called. At the beginning, do not do it.
Synchronized locks this method. When an object operates this method, other objects cannot operate. To prevent two objects from simultaneously operating this method.
Lazy Final Solution:

The code is as follows: Copy code
Class Single
{
Private static Single s = null;
Private Single (){}
Public static Single getInstance ()
 {
If (s = null)
  {
Synchronized (Single. class)
   {
If (s = null)
    {
S = new Single ();
    }
   }
  }
Return s;
 }
}

Remember principle: defines a singleton. We recommend that you use the hungry Chinese style.

01. Object-oriented (inheritance-Overview)

Inheritance: improves code reusability and links between classes to achieve polymorphism.
Note: do not inherit from other classes to simplify the code. You must have a class-to-class relationship before Inheritance. The class-to-class relationship is.

02. Object-oriented (inheritance-Overview)

In java, only single inheritance is supported, and multi-inheritance is not supported. Because inheritance is prone to security risks.
When multiple parent classes define the same function, when the function content is different, the subclass object is not sure which one to run.
However, java retains this mechanism and uses another embodiment to complete representation and implement multiple implementations.
Java supports multi-layer inheritance. That is, an inheritance system.
How to use the functions in an integration system?
To use the system, first check the description of the parent class in the system, because the parent class defines the common functions of the system. By understanding the common functions, then this system can be basically used.
In actual use, we need to create the objects of the most Subclass. Why? First, it is possible that the parent class cannot create objects. Second, you can use more functions to create subclass objects, including basic and specific features.
One simple sentence: query the parent class function and create a subclass object.

03. Object-oriented (clustering)

Aggregation: has a; clustering and combination.

04. Object-oriented (features of variables in the child parent class)

Class member:
Variable, function, constructor.
Variable: if a non-private variable of the same name appears in the sub-parent class, the sub-class must access the variable in this class and use this .; The subclass accesses the variable with the same name in the parent class and uses super.
This indicates the reference of the class object, and super indicates the reference of the parent class object.

05. Object-oriented (features of functions in the child parent class)

Features of functions in the child parent class:
When a subclass has the same function as the parent class, the subclass object calls this function and runs the content of the subclass function, just as the parent class function is overwritten, this is another feature of the function: rewrite (overwrite ).

When a subclass inherits the parent class and inherits the function of the parent class to the subclass, the content of the function is different from that of the parent class, there is no need to define new features, but to overwrite special features, retain the feature definition of the parent class, and override the feature content.

The subclass overwrites the parent class. You must ensure that the permission of the subclass is greater than or equal to that of the parent class. Otherwise, compilation fails. Static data can only overwrite static data.

Permission: all modifiers are not called default permissions, which are between the common and private permissions.

Remember:
The reload only looks at the parameter list of functions with the same name. Rewrite is the same as that of the word parent class.

06. Object-oriented (features of constructors in the child parent class-subclass instantiation process)

Features of constructor in sub-parent class:
The first line of the constructor of the subclass contains a line of statements: super ();
During initialization of the subclass object, the constructor of the parent class will also run because the first line of the constructor of the subclass has an implicit statement super () by default ();
Super (); accesses the constructor of the parent class's hollow parameter, and all the constructor in the subclass defaults to super ();
Why must the subclass access the constructor in the parent class? Because the data subclass in the parent class can be directly obtained, when the subclass object is created, you must first check how the parent class initializes the data, therefore, when initializing an object, the subclass must first access the constructor of the following parent class. If you want to access the constructor specified in the parent class, you can manually define super (parameter) in the first line of the constructor of a subclass. You can access the constructor of the parent class.
Subclass instantiation process:
Conclusion:
All constructors in the subclass access the constructor of the null parameter of the parent class by default, because the first line of each constructor in the subclass has an implicit super ();
If the parent class does not have a constructor, the subclass must manually specify the constructor in the parent class to be accessed in the form of a super statement.
Of course, the first line of the constructor of the subclass can also manually specify this statement to Access the constructor in this class. At least one constructor in the subclass will access the constructor in the parent class.

07. Object oriented (final)

Final Keywords:
(1) as a modifier, you can modify classes, variables, and functions.
(2) classes modified by final cannot be inherited. To avoid inheritance, the subclass rewrite function is blocked.
Inheritance poses a challenge to encapsulation.
(3) methods modified by final cannot be overwritten.
(4) a variable modified by final is a constant that can only be assigned a value once. It can be used to modify member variables or local variables. When describing a thing, the values of some data are fixed. In this case, to enhance readability, you need to give these values a name for easy reading, and this value does not need to be changed, therefore, the final modifier is used as a constant. The writing rules of constants are uppercase for all letters. If there are multiple words, words are connected by underscores.
(5) the internal class is defined on the local location of the class. It can only access the local variable modified by final.

08. Object-oriented (abstract class)

If multiple classes have the same functions but different feature subjects, you can extract them up. In this case, only the function definition is extracted, instead of the feature topic.
Abstract: This is what we cannot understand.
Features:
(1) abstract methods must be defined in abstract classes.
(2) abstract methods and abstract classes must be modified by abstract keywords.
(3) abstract classes cannot be used to create objects by the new keyword, because it is meaningless to call abstract methods.
(4) to use abstract class abstract methods, you must create a subclass object to call them after all abstract methods are repeatedly written by the subclass.
If a subclass overwrites some abstract methods, the subclass is still an abstract class.

09. Object-oriented (abstract class 2)

Abstract classes are not very different from general classes. How to describe things is how to describe things, but there are some incomprehensible things in the transaction. These uncertain parts are also the functions of the transaction, it must be explicit, but the subject cannot be defined. It is represented by an abstract method.

Abstract analogy generally involves abstract methods (functions ).
Abstract classes cannot be instantiated.
The role is not to allow this class to create objects.
Abstract classes do not define abstract methods. In this way, the class is not allowed to create objects.

10. Object-oriented (abstract class exercises)

11. Object-oriented (Template method mode)

Requirement: obtain the running time of a program.
Principle: Get and subtract the start time and end time of the program.
Method: use currentTimeMillis () of the System Class ();

After the code is optimized, this type of problem can be solved.
This is the template method design mode.
What is the template method?
When defining a function, some of the functions are definite, but some of them are uncertain. When determining the part and then using the uncertain part, the uncertain part will be exposed, and subclass of this class.

12. Object-oriented (interface)

Interface: it can be considered as a special abstract class in the initial stage. When methods in the abstract class are abstract, this class can be expressed through interfaces. Interface is used to define interfaces.
Features of interface definition:
(1) common definitions in interfaces: variables and abstract methods.
(2) the interface members all have fixed modifiers,
Constant: public static final
Method: public abstract
Remember: all the members in the interface are public.
The interface cannot create objects. Because there are abstract methods that need to be implemented by the quilt class, the subclass can be instantiated only after all the abstract methods in the interface are overwritten. Otherwise, the subclass is an abstract class.
After the interface is compiled, it is also a class file.

13. Object-oriented (Interface 2)

The interface can be implemented by multiple classes. It also does not support multi-inheritance and can implement multiple interfaces.
Implementation interface: implements
A class can implement multiple interfaces while inheriting a class.

Classes and classes are inherited, classes and interfaces are implemented, and interfaces are inherited.
Java can only implement multi-inheritance between interfaces.

14. Object-oriented (interface features)

Interface features:
Interfaces are rules for external leakage.
An interface is a function extension of a program.
Interface can be used for multiple implementations
There is a multi-implementation relationship between classes and interfaces, and classes can implement multiple interfaces while inheriting a class.
There can be multiple inheritance between interfaces

15. Object-oriented (interface example)

The basic functions are defined in the class, and the extended functions are defined in the interface.

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.