The distinction between static method and instance method

Source: Internet
Author: User

Java Series: Seemingly simple problems the difference between static and instanced methods

When the Java program startup class file is read, the class is loaded, if there is a static method, the memory is allocated at this time, the control store is allocated in memory when the non-static method instantiates the class , the reference is stored in the stack, and the entity is stored in the heap

The biggest difference is in memory.
Static methods generate memory at program start,The instance method generates memory in the program run,
So a static method can be called directly,instance method to genetic instance first,The method is called through the instance, which is very fast, but it takes up more memory.
Any language is a memory and disk operation Span style= "COLOR: #494949" >, As to whether object-oriented , Just a problem with the software layer , The bottom is the same , Only the implementation method is different.
static memory is a continuous ,, So of course there is no static method fast,
and static memory is limited, too many programs will not start.

The method is that we write every day, many programmers use the instantiation method, and seldom use static method, ask why do not say why, or simply answer the difference between the two definitions, static method does not need new to use the instantiation method needs new Before you can use .... Do we really understand that?

From the actual project development, there are three ways to develop the project:

In the development project , the BLL and dal are separated, and the dal code is called in the BLL .

One, using static methods in the DAL, without creating an instance of direct invocation (presumably many people develop it this way )

Class DAL
{
public static string GetUserName (...);
}
Called in the BLL :
DAL. GetUserName ();

II, dal (singleton) class DAL
{
public static readonly DAL Dal = new Dal ();
public string GetUserName (...);
}
in bll
DAL.dal.GetUserName ();

Third, use the instance method in the Dal to create an instance of the Dal object before each call:
Class DAL
{
public string GetUserName (...);
}
Called in the BLL :
Dal dal = new Dal ();
Dal. GetUserName ();

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

Development mode One: I think in some cases (such as calling multiple databases,GetUserName(...) Internal Processing Operations Section) is suspected of thread safety. This type of development is not a New object, so it is common.

Development Mode Two: should be more application in CS mode,DAL in the entire project will only have an object exists, if appear in b/S I think can not be compatible with a variety of problem situations. And also the problem of thread safety.

Development method Three: should be universally used, can be compatible with a variety of problems, and will not be a thread of unsafe suspicion appeared.

I purposely " how do you understand and use static methods and instantiate methods?" " This question asks a number of programmers who are developing different languages (C,C + +,java,C #)

Here are their answers:

Zhang Wei said:
There is almost no difference, if you do not need to instantiate, use static methods, if you want to be safe, use an instance method, so that other instance methods and variables can be called .

Shan said:
Static method is less useful, because he started on the instantiation, compared to the resources, of course, with the singleton mode is more useful
A lot of the use of data connections, I avoid the principle is to reduce resource consumption.

Zhang Xinbo said:
The static method means that I do not need to do a new operation on the class to which it belongs before the call , and I will use the static method primarily in the tool class.


to Detail said:
Static is a class, and an instance is an object.
One of the differences between static and instance methods is that static methods do not require attributes from the dependent class, and can be closed in this method to complete a function. Instance methods use more of the properties in the class.

Winson_ Zhang Lin said:
The biggest difference is in memory .
Static methods generate memory at the beginning of a program , and instance methods generate memory in a program run

Showlover said :
Static methods and instance methods have their own use ...

is defined as a static method , or as an instance method , also depends on the specific situation, such as the method itself and the type does not have too much relationship , can be defined as static method .

With an instance method , you need to create an instance first to invoke an instance method , while a static method does not .

performance , static method is slightly more efficient , But it will reside in memory ...
It's good to use static methods in some cases, because for a static method no matter how many instances you have,
One copy in memory to maintain. At the same time, some methods that do use static are the more appropriate .

Q.yuhen said :
This problem involves a lot of things, such as design patterns and so on. To put it simply, a static method is used to perform a full operation that is stateless, whereas an instance method is, in contrast, a part of a complete logic and needs to maintain a certain state value.
If you use Static method with memory and efficiency to differentiate ,Instance method goes back to the past structured programming. The fundamental starting point for using that approach is around object-oriented.

Chen Liang said:

A static method is similar to a global function, and an instance method is a method inside a class.

If you look at thread safety, performance, and compatibility, it is advisable to use the instantiation method.

Why do we divide the method area into: Static and instantiation methods?

If we continue to study in depth, we must leave the technology to talk about theory. Early structured programming, almost all methods are " static methods ", the introduction of the concept of instantiation is the object-oriented concept after the emergence of things, the distinction between static and instantiation methods can not only from the performance to understand, create C++,java, C # Such a master of object-oriented language introduction instantiation method must not be to solve what performance, memory problems, but to make development more stereotyped, object-oriented. In this case, the static method and the instantiation mode are differentiated to solve the problem of the pattern.

Take someone else an example to say things:

For example, " people " This class, everyone has a name, age, gender, height, etc., these attributes should be non-static, because each of these attributes are not the same, but the biology of which the door which is which the goal, this attribute belongs to the whole human, So it should be static - It does not depend on a particular person, and there is no one who is a " vertebrate mammal " and someone is " Artiodactyla " .

Java static initialization, instance initialization, and method of construction
There are three concepts that need to be understood first:
A Static initialization: Refers to the execution of content inside a static initialization block.
Two Instance initialization: Refers to the execution of the contents of an instance initialization block.
Three Constructor: A method with the same name as the name of the class, in particular, with no return value.
Let's take a look at the program results:

Execution Result:
This is static method~
This is static block
If you put

Note, the result of the operation is:
This is static method~
This is static block
Initialization block: 0
This was book ' s constructor~

Execution order: (Priority from high to low.) Static code block >main Method > Instance Initialization block > construct code block > Construction method. ”

Summarize:
The Java load class, the process of creating objects is explored only from the point of view of code execution, and does not go deep into the JVM mechanism.
1. The first time an object is created, the class to which the object belongs is loaded, that is, the corresponding. class file, and of course, if the class is already loaded and the object of the class is created again, the class is no longer needed. When a class loads, there are three parts that need to be loaded, a static variable, then a static method, and then a static initialization block. (See the first execution results, because there is no instance created so the initialization block does not execute)
2. It then starts to create an instance of the class, of course, if the static method is created with the object in the static initialization object, the class of the object continues to load, and the class of the object is loaded, of course, without having to load it again. So what is the process of creating an object instance? The first is the introduction of member variables, and then the instance initialization block, then the construction method, the construction method after the completion of the object to be created.
In this process, there are three, static initialization, instance initialization, and construction methods where you can actually write code execution. From the above analysis, we can see that the execution order of the three code blocks is the static initialization of the first class, then the initialization of the instance, and finally the execution of the construction method. That is, static initialization is a process of class loading, so it executes only once, and instance initialization is performed once per object creation, and the constructor is actually the same as the instance initialization, but it executes after the instance is initialized, and the construction method can overload multiple Which construction method to execute is based on your choice.
You can add a statement to the main () function to see:

At this point, the result is:
This is static method~
This is static block
Initialization block: 0
This was book ' s constructor~
Initialization block: 1
This was book ' s constructor~
This means that instance initialization is performed every time the object is created.

The distinction between static method and instance method

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.