Home Java javaTutorial Java basic introductory essay (8) JavaSE version - static static

Java basic introductory essay (8) JavaSE version - static static

Dec 22, 2016 pm 01:08 PM

Object-oriented (2)

this: represents the object. Which object does it represent? current object.

When member variables and local variables have the same name, you can use the keyword this to distinguish them.

This is the reference to the object to which the function belongs. (Simply put: which object calls the function where this is located, this represents that object.)

this can also be used to call other constructors in the constructor. Note: It can only be defined on the first line of the constructor. Because the initialization action must be performed first.

                                                                                                                                                                                                                                          person (String name) Objects of this class usually use this.

static:

Features: 1.static is a modifier used to modify members.

2. The members modified by static are shared by all objects.

3. Static exists prior to objects, because static members already exist as the class is loaded.修 4. Static modified members can be called directly by the class name, such as: class name. Member variables.

5. The data modified by static is shared data, and the time-specific data stored in the object is.

Note: Member variables are also called instance variables; variables modified by static are called static variables or class variables.

The difference between member variables and static variables:

1. The life cycles of the two variables are different.

Member variables exist with the creation of the object, and are recycled and released as the object is recycled;

Static variables exist with the loading of the class, and disappear with the disappearance of the class.

2. The calling methods are different.

Member variables can only be called by objects;

Static variables can be called by objects and class names (recommended).

3. The aliases are different.

Member variables are called instance variables;

Static variables are called class variables.

4. The data storage location is different.

Member variable data is stored in objects in heap memory, so it is also called object-specific data.

Static variable data is stored in the static area of ​​the method area (shared data area), so it is also called the shared data of the object.

Notes on static use:

1. Static methods can only access static members. (Non-static can access both static and non-static) (Note: Note that in the environment of the same class, static methods can only call static members of this class)

2. Cannot be used in static methods this or super keyword.

3. The main function is static.

When to use static?

1. Static variables.

When all the member variables in the analysis object are the same, then this member variable can be statically modified.

As long as the data is different in the object, it is the unique data of the object, which must be stored in the object and is non-static.

If it is the same data, the object does not need to be modified, it only needs to be used. It does not need to be stored in the object and is defined as static.

2. Static function.

Whether the function is statically modified, the only point of reference is whether the function has access to unique data in the object.

To put it simply, from the source code, whether the function needs to access non-static member variables, if so, the function is non-static. If not, the function can be defined as static.

Of course, this function can also be defined as non-static, but non-static needs to be called by an object, and only creating an object to call non-static methods without accessing unique data is meaningless when creating the object.

Special features of the main function:

1. The format is fixed; 2. It is recognized and called by jvm.

public: Because the permissions must be the greatest.

static: If you don’t need an object, just call it directly with the class name of the main function.

void: The main function has no specific return value.

main: function name, not a keyword, just a fixed name recognized by jvm.

String[] args: This is the parameter list of the main function. It is an array type parameter, and the elements are all string types. (It can be passed in when calling the main function, for example: java mainDemo xx yy zz is a string array with 3 elements passed in)

Static code block construction code block local code block:

Static code block: With Executed when the class is loaded. And only executed once. Function: Used to initialize the class.

Construction code block: executed as the object is created, and called several times when the object is created. Function: Can be initialized for all objects. (The difference from the constructor: The constructor performs targeted initialization of the corresponding object. The construction code block object initialization is universal.)

The role of local code blocks: limit the life cycle of local variables.

The calling sequence of the three is as follows:

class StaticCode
{
    static int num ;
    //静态代码块 (首先执行)
    static
    {
        num = 10;
//      num *=3;
        System.out.println("hahahah");
    }
    StaticCode(){}
 
    static void show()
    {
        System.out.println(num);
    }
}
 
class Person
{
    private String name;
     
     
 
    {//构造代码块。可以给所有对象进行初始化的。(如有调用对象,即其次调用,与局部代码块视情况而定)
 
        System.out.println("constructor code ");
//      cry();
    }
     
    static
    {
        System.out.println("static code");
    }
     
    Person()//是给对应的对象进行针对性的初始化。 
    {
        name = "baby";
//      cry();
    }
    Person(String name)
    {
        this.name  = name;
//      cry();
    }
    public void cry()
    {
        System.out.println("哇哇");
         
    }
 
    public void speak()
    {
        System.out.println("name:"+name);
    }
 
    static void show()
    {
        System.out.println("show run");
    }
}
 
 
class StaticCodeDemo 
{
    static
    {
//      System.out.println("a"); //先执行
    }
    public static void main(String[] args) 
    {
 
//      Person p = null;
//      p.speak();
 
//      Person.show();
//      Person p1 = new Person();
//      p1.speak();
//      Person p2 = new Person("旺财");
//      p2.speak();
//      new Person();
         
 
//      new StaticCode().show();
//      new StaticCode().show();
//      StaticCode.show();
//      System.out.println("b");    //后执行
    }
}
Copy after login

The above is the basic introduction to Java essay (8) JavaSE version - static content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles