国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java Javagetting Started What is java static

What is java static

Nov 14, 2019 am 11:58 AM
java static

What is java static

1. Static method

static method is generally called a static method because static method does not depend on any object It can be accessed, so for static methods, there is no this, because it is not attached to any object. Since there is no object, there is no this. And due to this feature, non-static member variables and non-static member methods of the class cannot be accessed in static methods, because non-static member methods/variables must rely on specific objects before they can be called.

But it should be noted that although non-static member methods and non-static member variables cannot be accessed in static methods, static member methods/variables can be accessed in non-static member methods. A simple example:

What is java static

In the above code, since the print2 method exists independently of the object, it can be called directly using the class name. If non-static methods/variables can be accessed in static methods, then if there is the following statement in the main method:

MyObject.print2();

There are no objects at this time, str2 does not exist at all, so There will be a conflict. The same is true for methods. Since you cannot predict whether non-static member variables are accessed in the print1 method, accessing non-static member methods in static member methods is also prohibited.

For non-static member methods, there is obviously no restriction on accessing static member methods/variables.

Therefore, if you want to call a method without creating an object, you can set this method to static. Our most common static method is the main method. As for why the main method must be static, it is now clear. Because the program does not create any objects when executing the main method, it can only be accessed through the class name.

Also remember, regarding whether the constructor is a static method, please refer to: http://blog.csdn.net/qq_17864929/article/details/48006835

2. Static variables

static variables are also called static variables. The difference between static variables and non-static variables is: static variables are shared by all objects, and there is only one in the memory. The copy is [stored in the method area], which will be initialized if and only when the class is loaded for the first time [the initialization locations of static variables with final and without final are different]. Non-static variables are owned by objects and are initialized when the object is created. There are multiple copies, and the copies owned by each object do not affect each other.

The initialization order of static member variables is initialized in the order in which they are defined.

3. Static code block

The static keyword also plays a key role in forming a static code block to optimize program performance. . A static block can be placed anywhere in a class, and there can be multiple static blocks in a class. When a class is loaded for the first time, each static block will be executed in the order of the static blocks, and will only be executed once [according to the class loading principle, each class is loaded once using parent delegation loading].

Initialization sequence static code block>Construction code block>Constructor function

public class Client {
{//構(gòu)造代碼塊
System.out.println("執(zhí)行構(gòu)造代碼塊");
}
}

Why static block can be used to optimize program performance is because of its characteristics: it will only be loaded when the class is loaded executed once. Let’s look at an example:

class Person{
private Date birthDate;
public Person(Date birthDate) {
this.birthDate = birthDate;
}
boolean isBornBoomer() {
Date startDate = Date.valueOf("1946");
Date endDate = Date.valueOf("1964");
return birthDate.compareTo(startDate)>=0 && birthDate.compareTo(endDate) < 0;
}
}

isBornBoomer is used to determine whether the person was born between 1946 and 1964. Every time isBornBoomer is called, two objects, startDate and birthDate, will be generated, resulting in a waste of space. If it is changed to this, the efficiency will be better. In fact, it uses the mechanism of loading static code blocks once in memory:

class Person{
private Date birthDate;
private static Date startDate,endDate;
static{
startDate = Date.valueOf("1946");
endDate = Date.valueOf("1964");
}
public Person(Date birthDate) {
this.birthDate = birthDate;
}
boolean isBornBoomer() {
return birthDate.compareTo(startDate)>=0 && birthDate.compareTo(endDate) < 0;
}
}

Therefore, many times some initialization operations that only need to be performed once are placed in static code block.

4. Static inner classes

This place does not write static inner classes separately, but deepens the understanding of static inner classes by comparing them with ordinary inner classes:

Why use inner classes?

1. Internal classes are generally only used by their external classes; [A good example of being used by external classes is that there is an internal class Entry in the hashmap collection, which is converted to hashmap storage for use]

2. The inner class provides some kind of window into the outer class. The inner class has a reference to the outer class, so the inner class can directly access the properties of the outer class;

3. It is also the most attractive reason. Each Inner classes can independently inherit an interface, regardless of whether the outer class has inherited an interface. Therefore, inner classes make the solution of multiple inheritance more complete.

A class defined inside a class is called an inner class, and a class containing an inner class is called an outer class. Inner classes can declare access restrictions such as public, protected, private, etc., they can be declared abstract for other inner classes or external classes to inherit and extend, or they can be declared static or final, or they can implement specific interfaces.

外部類按常規(guī)的類訪問方式(以對(duì)象的方式)使用內(nèi)部 類,唯一的差別是外部類可以訪問內(nèi)部類的所有方法與屬性,包括私有方法與屬性,外部類訪問內(nèi)部類,需要?jiǎng)?chuàng)建對(duì)象訪問;有一點(diǎn)需要注意,內(nèi)部類不能訪問外部類所在的局部變量,只能訪問final修飾的局部變量。

在方法內(nèi)定義內(nèi)部類時(shí),如果內(nèi)部類調(diào)用了方法中的變量,那么該變量必須申明為final類型,百思不得其解,后來想到應(yīng)該是生命周期的原因,因?yàn)榉椒▋?nèi)定義的變量是局部變量,離開該方法,變量就失去了作用,也就會(huì)自動(dòng)被消除,而內(nèi)部類卻不會(huì)離開它所在方法就失去作用,它有更廣的生命周期。

(1)創(chuàng)建實(shí)例

OutClass.InnerClass obj = outClassInstance.new InnerClass(); //注意是外部類實(shí)例.new,內(nèi)部類
AAA.StaticInner in = new AAA.StaticInner();//注意是外部類本身,靜態(tài)內(nèi)部類

(2)內(nèi)部類中的this

內(nèi)部類中的this與其他類一樣是指的本身。創(chuàng)建內(nèi)部類對(duì)象時(shí),它會(huì)與創(chuàng)造它的外圍對(duì)象有了某種聯(lián)系,于是能訪問外圍類的所有成員,不需任何特殊條件,可理解為內(nèi)部類鏈接到外部類。 用外部類創(chuàng)建內(nèi)部類對(duì)象時(shí),此內(nèi)部類對(duì)象會(huì)秘密的捕獲一個(gè)指向外部類的引用,于是,可以通過這個(gè)引用來訪問外圍類的成員。

(3)外部類訪問內(nèi)部類

內(nèi)部類類似外部類的屬性,因此訪問內(nèi)部類對(duì)象時(shí)總是需要一個(gè)創(chuàng)建好的外部類對(duì)象。外部類對(duì)象通過‘外部類名.this.xxx’的形式訪問內(nèi)部類的屬性與方法。如:

System.out.println("Print in inner Outer.index=" + pouter.this.index);
System.out.println("Print in inner Inner.index=" + this.index);

(4)內(nèi)部類向上轉(zhuǎn)型

內(nèi)部類也可以和普通類一樣擁有向上轉(zhuǎn)型的特性。將內(nèi)部類向上轉(zhuǎn)型為基類型,尤其是接口時(shí),內(nèi)部類就有了用武之地。如果內(nèi)部類是private的,只可以被它的外部類問,從而完全隱藏實(shí)現(xiàn)的細(xì)節(jié)。

(5)方法內(nèi)的類

方法內(nèi)創(chuàng)建的類(注意方法中也能定義類),不能加訪問修飾符。另外,方法內(nèi)部的類也不是在調(diào)用方法時(shí)才會(huì)創(chuàng)建的,它們一樣也被事先編譯了。

(6)靜態(tài)內(nèi)部類

定義靜態(tài)內(nèi)部類:在定義內(nèi)部類的時(shí)候,可以在其前面加上一個(gè)權(quán)限修飾符static。此時(shí)這個(gè)內(nèi)部類就變?yōu)榱遂o態(tài)內(nèi)部類。

通常稱為嵌套類,當(dāng)內(nèi)部類是static時(shí),意味著:

[1]要?jiǎng)?chuàng)建嵌套類的對(duì)象,并不需要其外圍類的對(duì)象;

[2]不能從嵌套類的對(duì)象中訪問非靜態(tài)的外圍類對(duì)象(不能夠從靜態(tài)內(nèi)部類的對(duì)象中訪問外部類的非靜態(tài)成員);

嵌 套類與普通的內(nèi)部類還有一個(gè)區(qū)別:普通內(nèi)部類的字段與方法,只能放在類的外部層次上,所以普通的內(nèi)部類不能有static數(shù)據(jù)和static字段, 也不能包含嵌套類。但是在嵌套類里可以包含所有這些東西。也就是說,在非靜態(tài)內(nèi)部類中不可以聲明靜態(tài)成員,只有將某個(gè)內(nèi)部類修飾為靜態(tài)類,然后才能夠在這 個(gè)類中定義靜態(tài)的成員變量與成員方法。

另外,在創(chuàng)建靜態(tài)內(nèi)部類時(shí)不需要將靜態(tài)內(nèi)部類的實(shí)例綁定在外部類的實(shí)例上。普通非靜態(tài)內(nèi)部類的 對(duì)象是依附在外部類對(duì)象之中的,要在一個(gè)外部類中定義一個(gè)靜態(tài)的內(nèi)部類,不需要利用關(guān)鍵字new來創(chuàng)建內(nèi)部類的實(shí)例。靜態(tài)類和方法只屬于類本身,并不屬于 該類的對(duì)象,更不屬于其他外部類的對(duì)象。

(7)內(nèi)部類標(biāo)識(shí)符

每個(gè)類會(huì)產(chǎn)生一個(gè).class文件,文件名即為類名。同樣,內(nèi)部類也會(huì)產(chǎn)生這么一個(gè).class文件,但是它的名稱卻不是內(nèi)部類的類名,而是有著嚴(yán)格的限制:外圍類的名字,加上$,再加上內(nèi)部類名字。

代碼具體:

public class OutClassTest 
{
static int a;
int b;
public static void test() {
System.out.println("outer class static function");
}
public static void main(String[] args) {
// new一個(gè)外部類
OutClassTest oc1 = new OutClassTest();
// 通過外部類的對(duì)象new一個(gè)非靜態(tài)的內(nèi)部類
OutClassTest.InnerClass no_static_inner = oc1.new InnerClass();
// 調(diào)用非靜態(tài)內(nèi)部類的方法
System.out.println(no_static_inner.getKey());
// 調(diào)用靜態(tài)內(nèi)部類的靜態(tài)變量
System.out.println(OutClassTest.InnerStaticClass.static_value);
// 不依賴于外部類實(shí)例,直接實(shí)例化內(nèi)部靜態(tài)類
OutClassTest.InnerStaticClass inner = new OutClassTest.InnerStaticClass();
// 調(diào)用靜態(tài)內(nèi)部類的非靜態(tài)方法
System.out.println(inner.getValue());
// 調(diào)用內(nèi)部靜態(tài)類的靜態(tài)方法
System.out.println(OutClassTest.InnerStaticClass.getMessage());
}
private class InnerClass {
// 只有在靜態(tài)內(nèi)部類中才能夠聲明或定義靜態(tài)成員
// private static String tt = "0";
private int flag = 0;
public InnerClass() {
// 三.非靜態(tài)內(nèi)部類的非靜態(tài)成員可以訪問外部類的非靜態(tài)變量和靜態(tài)變量
System.out.println("InnerClass create a:" + a);
System.out.println("InnerClass create b:" + b);
System.out.println("InnerClass create flag:" + flag);
//
System.out.println("InnerClass call outer static function");
// 調(diào)用外部類的靜態(tài)方法
test();
}
public  String getKey() {
return "no-static-inner";
}
}
private static class InnerStaticClass {
// 靜態(tài)內(nèi)部類可以有靜態(tài)成員,而非靜態(tài)內(nèi)部類則不能有靜態(tài)成員。
private static String static_value = "0";
private int flag = 0;
public InnerStaticClass() {
System.out.println("InnerClass create a:" + a);
            // 靜態(tài)內(nèi)部類不能夠訪問外部類的非靜態(tài)成員
            // System.out.println("InnerClass create b:" + b);
            System.out.println("InnerStaticClass flag is " + flag);
            System.out.println("InnerStaticClass tt is " + static_value);
        }
        public int getValue() {
            // 靜態(tài)內(nèi)部類訪問外部類的靜態(tài)方法
            test();
            return 1;
        }
        public static String getMessage() {
            return "static-inner";
        }
    }
    public OutClassTest() {
        // new一個(gè)非靜態(tài)的內(nèi)部類
        InnerClass ic = new InnerClass();
        System.out.println("OuterClass create");
    }
}

有就是類名ClassName后面多了個(gè).* ,意思是導(dǎo)入這個(gè)類里的靜態(tài)方法。當(dāng)然,也可以只導(dǎo)入某個(gè)靜態(tài)方法,只要把 .* 換成靜態(tài)方法名就行了。然后在這個(gè)類中,就可以直接用方法名調(diào)用靜態(tài)方法,而不必用ClassName.方法名 的方式來調(diào)用。

好處:這種方法的好處就是可以簡化一些操作,例如打印操作System.out.println(…);就可以將其寫入一個(gè)靜態(tài)方法print(…),在使用時(shí)直接print(…)就可以了。但是這種方法建議在有很多重復(fù)調(diào)用的時(shí)候使用,如果僅有一到兩次調(diào)用,不如直接寫來的方便

example:

在Java 5中,import語句得到了增強(qiáng),以便提供甚至更加強(qiáng)大的減少擊鍵次數(shù)功能,雖然一些人爭議說這是以可讀性為代價(jià)的。這種新的特性成為靜態(tài)導(dǎo)入。當(dāng)你想使用static成員時(shí),可以使用靜態(tài)導(dǎo)入(在API中的類和你自己的類上,都可以使用該特性)。下面是靜態(tài)導(dǎo)入前后的代碼實(shí)例:

在靜態(tài)導(dǎo)入之前:

public class TestStatic {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.toHexString(42));
}
}

在靜態(tài)導(dǎo)入之后:

import static java.lang.System.out;
import static java.lang.Integer.*;
public class TestStaticImport {
public static void main(String[] args) {
out.println(MAX_VALUE);
out.println(toHexString(42));
}
}

讓我們看一下使用靜態(tài)導(dǎo)入特性的代碼中將發(fā)生什么:

1. Although this feature is often called "static import", the syntax must be import static, followed by the fully qualified name of the static member you want to import, or a wildcard character. In this example, we make a static import on the out object of the System class.

2. In this example, we may want to use several static members of the java.lang.Integer class. This static import statement uses wildcards to say "I want to do a static import on all static members in this class".

3. Now we finally see the benefits of the static import feature! We don't have to type System in System.out.println. Very good! Also, we don't have to type Integer in Integer.MAX_VALUE. So, in this line of code, we are able to use a shortcut for a static method and a constant.

4. Finally, we perform more shortcut operations, this time for methods of the Integer class.

We've been getting a bit sarcastic about this feature, but we're not alone. We don't think saving a few keystrokes makes the code any harder to read, but many developers have asked for it to be added to the language.

The following are several principles for using static import:

You must say import static, not static import.

Beware of ambiguously named static members. For example, if you perform static imports on the Integer class and the Long class, referencing MAX_VALUE will cause a compiler error because both Integer and Long have a MAX_VALUE constant, and Java will not know which MAX_VALUE you are referencing.

You can perform static imports on static object references, constants (remember, they are static or final) and static methods.

Many java training videos, all on the PHP Chinese website, welcome to learn online!

The above is the detailed content of What is java static. For more information, please follow other related articles on the PHP Chinese website!

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1501
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles