简体   繁体   English

类中的“静态”关键字有什么作用?

[英]What does the 'static' keyword do in a class?

To be specific, I was trying this code:具体来说,我正在尝试以下代码:

package hello;

public class Hello {

    Clock clock = new Clock();

    public static void main(String args[]) {
        clock.sayTime();
    }
}

But it gave the error但它给出了错误

Cannot access non-static field in static method main无法访问静态方法 main 中的非静态字段

So I changed the declaration of clock to this:所以我把clock的声明改成这样:

static Clock clock = new Clock();

And it worked.它奏效了。 What does it mean to put that keyword before the declaration?将关键字放在声明之前是什么意思? What exactly will it do and/or restrict in terms of what can be done to that object?就可以对该对象执行的操作而言,它究竟会做什么和/或限制什么?

static members belong to the class instead of a specific instance. static成员属于类而不是特定实例。

It means that only one instance of a static field exists [1] even if you create a million instances of the class or you don't create any.这意味着只有一个static字段的实例存在[1] ,即使您创建了一百万个该类的实例或者您没有创建任何实例。 It will be shared by all instances.它将由所有实例共享。

Since static methods also do not belong to a specific instance, they can't refer to instance members.由于static方法也不属于特定实例,因此它们不能引用实例成员。 In the example given, main does not know which instance of the Hello class (and therefore which instance of the Clock class) it should refer to.在给出的示例中, main不知道应该引用Hello类的哪个实例(因此也不知道Clock类的哪个实例)。 static members can only refer to static members. static成员只能引用static成员。 Instance members can, of course access static members.实例成员当然可以访问static成员。

Side note: Of course, static members can access instance members through an object reference .旁注:当然, static成员可以通过对象引用访问实例成员。

Example:例子:

public class Example {
    private static boolean staticField;
    private boolean instanceField;
    public static void main(String[] args) {
        // a static method can access static fields
        staticField = true;

        // a static method can access instance fields through an object reference
        Example instance = new Example();
        instance.instanceField = true;
    }

[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point. [1]:根据运行时特性,它可以是每个 ClassLoader 或 AppDomain 或线程一个,但这不是重点。

It means that there is only one instance of "clock" in Hello, not one per each separate instance of the "Hello" class, or more-so, it means that there will be one commonly shared "clock" reference among all instances of the "Hello" class.这意味着 Hello 中只有一个“时钟”实例,而不是每个单独的“Hello”类实例都有一个,或者更多,这意味着在所有实例之间将有一个共同共享的“时钟”引用“你好”类。

So if you were to do a "new Hello" anywhere in your code: A- in the first scenario (before the change, without using "static"), it would make a new clock every time a "new Hello" is called, but B- in the second scenario (after the change, using "static"), every "new Hello" instance would still share and use the initial and same "clock" reference first created.因此,如果您要在代码中的任何位置执行“新 Hello”: A- 在第一个场景中(在更改之前,不使用“静态”),每次调用“新 Hello”时都会生成一个新时钟,但是 B- 在第二种情况下(更改后,使用“静态”),每个“新 Hello”实例仍将共享并使用最初创建的相同“时钟”引用。

Unless you needed "clock" somewhere outside of main, this would work just as well:除非您在 main 之外的某个地方需要“时钟”,否则这也可以:

package hello;
public class Hello
{
    public static void main(String args[])
    {
      Clock clock=new Clock();
      clock.sayTime();    
    }
}

The static keyword means that something (a field, method or nested class) is related to the type rather than any particular instance of the type. static关键字意味着某些东西(字段、方法或嵌套类)与类型相关,而不是与该类型的任何特定实例相关。 So for example, one calls Math.sin(...) without any instance of the Math class, and indeed you can't create an instance of the Math class.例如,在没有任何Math类实例的情况下调用Math.sin(...) ,实际上您无法创建Math类的实例。

For more information, see the relevant bit of Oracle's Java Tutorial .有关更多信息,请参阅Oracle 的 Java 教程的相关部分。


Sidenote边注

Java unfortunately allows you to access static members as if they were instance members, eg不幸的是,Java允许您像访问实例成员一样访问静态成员,例如

// Bad code!
Thread.currentThread().sleep(5000);
someOtherThread.sleep(5000);

That makes it look as if sleep is an instance method, but it's actually a static method - it always makes the current thread sleep.这使它看起来好像sleep是一个实例方法,但它实际上是一个静态方法 - 它总是使当前线程休眠。 It's better practice to make this clear in the calling code:最好在调用代码中明确这一点:

// Clearer
Thread.sleep(5000);

The static keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type , not the actual objects themselves. Java 中的static关键字意味着变量或函数在该类的所有实例之间共享,因为它属于type ,而不是实际的对象本身。

So if you have a variable: private static int i = 0;所以如果你有一个变量: private static int i = 0; and you increment it ( i++ ) in one instance, the change will be reflected in all instances.并且您在一个实例中增加它( i++ ),更改将反映在所有实例中。 i will now be 1 in all instances. i现在在所有情况下都是 1。

Static methods can be used without instantiating an object.无需实例化对象即可使用静态方法。

Basic usage of static members...静态成员的基本用法...

public class Hello
{
    // value / method
    public static String staticValue;
    public String nonStaticValue;
}

class A
{
    Hello hello = new Hello();
    hello.staticValue = "abc";
    hello.nonStaticValue = "xyz";
}

class B
{
    Hello hello2 = new Hello(); // here staticValue = "abc"
    hello2.staticValue; // will have value of "abc"
    hello2.nonStaticValue; // will have value of null
}

That's how you can have values shared in all class members without sending class instance Hello to other class.这就是您可以在所有类成员中共享值的方式,而无需将类实例 Hello 发送到其他类。 And whit static you don't need to create class instance.而且你不需要创建类实例。

Hello hello = new Hello();
hello.staticValue = "abc";

You can just call static values or methods by class name:您可以通过类名调用静态值或方法:

Hello.staticValue = "abc";

Static means that you don't have to create an instance of the class to use the methods or variables associated with the class.静态意味着您不必创建类的实例即可使用与类关联的方法或变量。 In your example, you could call:在您的示例中,您可以调用:

Hello.main(new String[]()) //main(...) is declared as a static function in the Hello class

directly, instead of:直接,而不是:

Hello h = new Hello();
h.main(new String[]()); //main(...) is a non-static function linked with the "h" variable

From inside a static method (which belongs to a class) you cannot access any members which are not static, since their values depend on your instantiation of the class.从静态方法(属于类)内部,您无法访问任何非静态成员,因为它们的值取决于您对类的实例化。 A non-static Clock object, which is an instance member, would have a different value/reference for each instance of your Hello class, and therefore you could not access it from the static portion of the class.作为实例成员的非静态时钟对象对于 Hello 类的每个实例都有不同的值/引用,因此您无法从类的静态部分访问它。

Static in Java: Java中的静态:

Static is a Non Access Modifier.静态是非访问修饰符。 The static keyword belongs to the class than instance of the class. static 关键字属于类而不是类的实例。 can be used to attach a Variable or Method to a Class.可用于将变量或方法附加到类。

Static keyword CAN be used with:静态关键字可用于:

Method方法

Variable多变的

Class nested within another Class嵌套在另一个类中的类

Initialization Block初始化块

CAN'T be used with:不能用于:

Class (Not Nested)类(未嵌套)

Constructor构造函数

Interfaces接口

Method Local Inner Class(Difference then nested class)方法局部内部类(差异然后嵌套类)

Inner Class methods内部类方法

Instance Variables实例变量

Local Variables局部变量

Example:例子:

Imagine the following example which has an instance variable named count which in incremented in the constructor:想象一下下面的例子,它有一个名为 count 的实例变量,它在构造函数中递增:

package pkg;

class StaticExample {
    int count = 0;// will get memory when instance is created

    StaticExample() {
        count++;
        System.out.println(count);
    }

    public static void main(String args[]) {

        StaticExample c1 = new StaticExample();
        StaticExample c2 = new StaticExample();
        StaticExample c3 = new StaticExample();

    }
}

Output:输出:

1 1 1 1 1 1

Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.由于实例变量在对象创建时就获得了内存,所以每个对象都会有实例变量的副本,如果递增,就不会反映到其他对象。

Now if we change the instance variable count to a static one then the program will produce different output:现在,如果我们将实例变量 count 更改为静态变量,那么程序将产生不同的输出:

package pkg;

class StaticExample {
    static int count = 0;// will get memory when instance is created

    StaticExample() {
        count++;
        System.out.println(count);
    }

    public static void main(String args[]) {

        StaticExample c1 = new StaticExample();
        StaticExample c2 = new StaticExample();
        StaticExample c3 = new StaticExample();

    }
}

Output:输出:

1 2 3 1 2 3

In this case static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.在这种情况下,静态变量只会获得一次内存,如果任何对象更改了静态变量的值,它将保留其值。

Static with Final:静态与最终:

The global variable which is declared as final and static remains unchanged for the whole execution.声明为final 和 static的全局变量在整个执行过程中保持不变。 Because, Static members are stored in the class memory and they are loaded only once in the whole execution.因为,静态成员存储在类内存中,并且在整个执行过程中只加载一次。 They are common to all objects of the class.它们对类的所有对象都是通用的。 If you declare static variables as final, any of the objects can't change their value as it is final.如果将静态变量声明为 final,则任何对象都无法更改其值,因为它是 final。 Therefore, variables declared as final and static are sometimes referred to as Constants.因此,声明为 final 和 static 的变量有时称为常量。 All fields of interfaces are referred as constants, because they are final and static by default.接口的所有字段都称为常量,因为默认情况下它们是最终的和静态的。

在此处输入图像描述

Picture Resource : Final Static图片资源:最终静态

To add to existing answers, let me try with a picture:要添加到现有答案,让我尝试使用图片:

An interest rate of 2% is applied to ALL savings accounts. 2% 的利率适用于所有储蓄账户。 Hence it is static .因此它是静态的。

A balance should be individual , so it is not static.平衡应该是个体的,所以它不是静态的。

在此处输入图像描述

This discussion has so far ignored classloader considerations.到目前为止,这个讨论忽略了类加载器的考虑。 Strictly speaking, Java static fields are shared between all instances of a class for a given classloader .严格来说,Java 静态字段在给定类加载器的类的所有实例之间共享。

The keyword static is used to denote a field or a method as belonging to the class itself and not the instance.关键字static用于表示属于类本身而不是实例的字段或方法。 Using your code, if the object Clock is static, all of the instances of the Hello class will share this Clock data member (field) in common.使用您的代码,如果对象Clock是静态的,则Hello类的所有实例将共享此Clock数据成员(字段)。 If you make it non-static, each individual instance of Hello can have a unique Clock field.如果将其设为非静态,则Hello的每个单独实例都可以有一个唯一的Clock字段。

You added a main method to your class Hello so that you could run the code.您向Hello类添加了一个main方法,以便您可以运行代码。 The problem with that is that the main method is static and as such, it cannot refer to non-static fields or methods inside of it.问题在于main方法是静态的,因此它不能引用其中的非静态字段或方法。 You can resolve this in two ways:您可以通过两种方式解决此问题:

  1. Make all fields and methods of the Hello class static so that they could be referred to inside the main method.Hello类的所有字段和方法设为静态,以便可以在main方法中引用它们。 This is really not a good thing to do (or the wrong reason to make a field and/or a method static)这真的不是一件好事(或者使字段和/或方法静态的错误原因)
  2. Create an instance of your Hello class inside the main method and access all it's fields and methods the way they were intended to in the first place.在 main 方法中创建Hello类的实例,并按照最初的预期方式访问它的所有字段和方法。

For you, this means the following change to your code:对您而言,这意味着对您的代码进行以下更改:

package hello;

public class Hello {

    private Clock clock = new Clock();

    public Clock getClock() {
        return clock;
    }

    public static void main(String args[]) {
        Hello hello = new Hello();
        hello.getClock().sayTime();
    }
}

A field can be assigned to either the class or an instance of a class.可以将字段分配给类或类的实例。 By default fields are instance variables.默认情况下,字段是实例变量。 By using static the field becomes a class variable, thus there is one and only one clock .通过使用static字段成为一个类变量,因此只有一个clock If you make a changes in one place, it's visible everywhere.如果您在一个地方进行更改,它在任何地方都可见。 Instance varables are changed independently of one another.实例变量彼此独立地更改。

In Java, the static keyword can be simply regarded as indicating the following:在 Java 中, static关键字可以简单地认为表示以下内容:

"without regard or relationship to any particular instance" “不考虑或与任何特定实例有关”

If you think of static in this way, it becomes easier to understand its use in the various contexts in which it is encountered:如果您以这种方式考虑static ,则更容易理解它在遇到它的各种上下文中的使用:

  • A static field is a field that belongs to the class rather than to any particular instance static字段是属于类而不是任何特定实例的字段

  • A static method is a method that has no notion of this ; static方法是没有this概念的方法; it is defined on the class and doesn't know about any particular instance of that class unless a reference is passed to it它是在类上定义的,并且不知道该类的任何特定实例,除非将引用传递给它

  • A static member class is a nested class without any notion or knowledge of an instance of its enclosing class (unless a reference to an enclosing class instance is passed to it) static成员类是一个嵌套类,对其封闭类的实例没有任何概念或知识(除非将对封闭类实例的引用传递给它)

I have developed a liking for static methods (only, if possible) in "helper" classes.我已经对“助手”类中的静态方法(仅在可能的情况下)产生了兴趣。

The calling class need not create another member (instance) variable of the helper class.调用类不需要创建帮助类的另一个成员(实例)变量。 You just call the methods of the helper class.您只需调用助手类的方法。 Also the helper class is improved because you no longer need a constructor, and you need no member (instance) variables.辅助类也得到了改进,因为您不再需要构造函数,并且不需要成员(实例)变量。

There are probably other advantages.可能还有其他优点。

Static makes the clock member a class member instead of an instance member.静态使时钟成员成为类成员而不是实例成员。 Without the static keyword you would need to create an instance of the Hello class (which has a clock member variable) - eg如果没有 static 关键字,您将需要创建 Hello 类的实例(它有一个时钟成员变量) - 例如

Hello hello = new Hello();
hello.clock.sayTime();

静态方法不使用定义它们的类的任何实例变量。可以在此页面上找到对差异的很好解释

//Here is an example 

public class StaticClass 
{
    static int version;
    public void printVersion() {
         System.out.println(version);
    }
}

public class MainClass 
{
    public static void main(String args[]) {  
        StaticClass staticVar1 = new StaticClass();
        staticVar1.version = 10;
        staticVar1.printVersion() // Output 10

        StaticClass staticVar2 = new StaticClass();
        staticVar2.printVersion() // Output 10
        staticVar2.version = 20;
        staticVar2.printVersion() // Output 20
        staticVar1.printVersion() // Output 20
    }
}

Can also think of static members not having a "this" pointer.还可以考虑没有“this”指针的静态成员。 They are shared among all instances.它们在所有实例之间共享。

Understanding Static concepts了解静态概念

public class StaticPractise1 {
    public static void main(String[] args) {
        StaticPractise2 staticPractise2 = new StaticPractise2();
        staticPractise2.printUddhav(); //true
        StaticPractise2.printUddhav(); /* false, because printUddhav() is although inside StaticPractise2, but it is where exactly depends on PC program counter on runtime. */

        StaticPractise2.printUddhavsStatic1(); //true
        staticPractise2.printUddhavsStatic1(); /*false, because, when staticPractise2 is blueprinted, it tracks everything other than static  things and it organizes in its own heap. So, class static methods, object can't reference */

    }
}

Second Class二等舱

public class StaticPractise2 {
    public static void printUddhavsStatic1() {
        System.out.println("Uddhav");
    }

    public void printUddhav() {
        System.out.println("Uddhav");
    }
}

main() is a static method which has two fundamental restrictions: main()是一个静态方法,它有两个基本限制:

  1. The static method cannot use a non-static data member or directly call non-static method.静态方法不能使用非静态数据成员或直接调用非静态方法。
  2. this() and super() cannot be used in static context. this()super()不能在静态上下文中使用。

     class A { int a = 40; //non static public static void main(String args[]) { System.out.println(a); } }

Output: Compile Time Error输出:编译时错误

Static Variables Can only be accessed only in static methods, so when we declare the static variables those getter and setter methods will be static methods静态变量只能在静态方法中访问,所以当我们声明静态变量时,getter和setter方法将是静态方法

static methods is a class level we can access using class name静态方法是我们可以使用类名访问的类级别

The following is example for Static Variables Getters And Setters:以下是静态变量 Getter 和 Setter 的示例:

public class Static 
{

    private static String owner;
    private static int rent;
    private String car;
    public String getCar() {
        return car;
    }
    public void setCar(String car) {
        this.car = car;
    }
    public static int getRent() {
        return rent;
    }
    public static void setRent(int rent) {
        Static.rent = rent;
    }
    public static String getOwner() {
        return owner;
    }

    public static void setOwner(String owner) {
        Static.owner = owner;
    }

}

A question was asked here about the choice of the word 'static' for this concept. 这里提出了一个关于为这个概念选择“静态”这个词的问题。 It was dup'd to this question, but I don't think the etymology has been clearly addressed.这是对这个问题的欺骗,但我认为词源没有得到明确解决。 So...所以...


It's due to keyword reuse, starting with C.这是由于关键字重用,从 C 开始。

Consider data declarations in C (inside a function body):考虑 C 中的数据声明(在函数体内):

    void f() {
        int foo = 1;
        static int bar = 2;
         :
    }

The variable foo is created on the stack when the function is entered (and destroyed when the function terminates).变量 foo 在进入函数时在堆栈上创建(并在函数终止时销毁)。 By contrast, bar is always there, so it's 'static' in the sense of common English - it's not going anywhere.相比之下, bar 总是在那里,所以它在普通英语的意义上是“静态的”——它不会去任何地方。

Java, and similar languages, have the same concept for data. Java 和类似的语言对数据有相同的概念。 Data can either be allocated per instance of the class (per object) or once for the entire class.可以为每个类的实例(每个对象)分配数据,也可以为整个类分配一次。 Since Java aims to have familiar syntax for C/C++ programmers, the 'static' keyword is appropriate here.由于 Java 旨在为 C/C++ 程序员提供熟悉的语法,因此“静态”关键字在这里是合适的。

    class C {
        int foo = 1;
        static int bar = 2;
         :
    }

Lastly, we come to methods.最后,我们来谈谈方法。

    class C {
        int foo() { ... }
        static int bar() { ... }
         :
    }

There is, conceptually speaking, an instance of foo() for every instance of class C. There is only one instance of bar() for the entire class C. This is parallel to the case we discussed for data, and therefore using 'static' is again a sensible choice, especially if you don't want to add more reserved keywords to your language.从概念上讲,类 C 的每个实例都有一个 foo() 实例。整个 C 类只有一个 bar() 实例。这与我们讨论的数据情况类似,因此使用 'static ' 又是一个明智的选择,特别是如果您不想在您的语言中添加更多保留关键字。

When run some project firstly load static things(variables, methods, blocks..). 在运行某些项目时,首先要加载静态内容(变量,方法,块..)。

When run this project main method load first. 运行此项目时,首先加载主方法。 Because its static method . 因为它是static method Then it look object "a" object .But object a not define yet. 然后,它看起来是对象"a" object 。但是对象a尚未定义。 Because its non static. 因为它是非静态的。 Then come like this error. 然后出现此错误。

A member in a Java program can be declared as static using the keyword “static” preceding its declaration/definition. Java 程序中的成员可以使用其声明/定义之前的关键字“static”声明为静态的。 When a member is declared static, then it essentially means that the member is shared by all the instances of a class without making copies of per instance.当一个成员被声明为静态时,它本质上意味着该成员由一个类的所有实例共享,而无需为每个实例制作副本。

Thus static is a non-class modifier used in Java and can be applied to the following members:因此 static 是 Java 中使用的非类修饰符,可以应用于以下成员:

  • Variables变量
  • Methods方法
  • Blocks
  • Classes (more specifically, nested classes)类(更具体地说,嵌套类)

When a member is declared static, then it can be accessed without using an object.当一个成员被声明为静态的,那么它就可以在不使用对象的情况下被访问。 This means that before a class is instantiated, the static member is active and accessible.这意味着在类被实例化之前,静态成员是活动的并且是可访问的。 Unlike other non-static class members that cease to exist when the object of the class goes out of scope, the static member is still obviously active.与当类的对象超出范围时不再存在的其他非静态类成员不同,静态成员显然仍然是活动的。

Static Variable in Java Java中的静态变量

A member variable of a class that is declared as static is called the Static Variable.声明为静态的类的成员变量称为静态变量。 It is also called as the “Class variable”.它也被称为“类变量”。 Once the variable is declared as static, memory is allocated only once and not every time when a class is instantiated.一旦变量被声明为静态,内存只分配一次,而不是每次实例化类时。 Hence you can access the static variable without a reference to an object.因此,您可以在不引用对象的情况下访问静态变量。

The following Java program depicts the usage of Static variables:以下 Java 程序描述了静态变量的用法:

class Main
{
// static variables a and b
static int a = 10;
static int b;

static void printStatic()
{
    a = a /2;
    b = a;

    System.out.println("printStatic::Value of a : "+a + " Value of b : 
 "+b);
}  

public static void main(String[] args)
{
   printStatic();
   b = a*5;
   a++;

System.out.println("main::Value of a : "+a + " Value of b : "+b);
   }
 }

output::输出::

printStatic::Value of a : Value of b : 5
main::Value of a : 6 Value of b : 25

In the above program, we have two static variables ie a and b.在上面的程序中,我们有两个静态变量,即 a 和 b。 We modify these variables in a function “printStatic” as well as in “main”.我们在函数“printStatic”和“main”中修改这些变量。 Note that the values of these static variables are preserved across the functions even when the scope of the function ends.请注意,即使函数范围结束,这些静态变量的值也会在函数中保留。 The output shows the values of variables in two functions.输出显示两个函数中的变量值。

Static Method静态方法

A method in Java is static when it is preceded by the keyword “static”.当 Java 中的方法前面带有关键字“static”时,它就是静态的。

Some points that you need to remember about the static method include:关于静态方法,您需要记住的一些要点包括:

  • A static method belongs to the class as against other non-static methods that are invoked using the instance of a class.与使用类的实例调用的其他非静态方法相比,静态方法属于该类。
  • To invoke a static method, you don't need a class object.要调用静态方法,您不需要类对象。
  • The static data members of the class are accessible to the static method.静态方法可以访问类的静态数据成员。 The static method can even change the values of the static data member.静态方法甚至可以更改静态数据成员的值。
  • A static method cannot have a reference to 'this' or 'super' members.静态方法不能引用“this”或“super”成员。 Even if a static method tries to refer them, it will be a compiler error.即使静态方法尝试引用它们,也会出现编译器错误。
  • Just like static data, the static method can also call other static methods.就像静态数据一样,静态方法也可以调用其他静态方法。 A static method cannot refer to non-static data members or variables and cannot call non-static methods too.静态方法不能引用非静态数据成员或变量,也不能调用非静态方法。

The following program shows the implementation of the static method in Java:以下程序显示了 Java 中静态方法的实现:

class Main
{
  // static method
  static void static_method()
{
    System.out.println("Static method in Java...called without any 
object");
}

public static void main(String[] args)
{
    static_method();
   }
 }

output:输出:

Static method in Java...called without any object

Static Block In Java Java中的静态块

Just as you have function blocks in programming languages like C++, C#, etc. in Java also, there is a special block called “static” block that usually includes a block of code related to static data.就像您在 Java 中的 C++、C# 等编程语言中具有功能块一样,也有一个称为“静态”块的特殊块,它通常包含与静态数据相关的代码块。

This static block is executed at the moment when the first object of the class is created (precisely at the time of classloading) or when the static member inside the block is used.此静态块在创建类的第一个对象时(准确地说是在类加载时)或使用块内的静态成员时执行。

The following program shows the usage of a static block.以下程序显示了静态块的用法。

class Main
{
  static int sum = 0;
  static int val1 = 5;
  static int val2;

// static block
 static {
    sum = val1 + val2;
    System.out.println("In static block, val1: " + val1  + " val2: "+ 
val2 + " sum:" + sum);
    val2 = val1 * 3;
    sum = val1 + val2;
}

 public static void main(String[] args)
{
    System.out.println("In main function, val1: " + val1  + " val2: "+ val2 + " sum:" + sum);
  }
}

output:输出:

In static block, val1: 5 val2: 0 sum:5
In main function, val1: val2: 15 sum:20

Static Class静态类

In Java, you have static blocks, static methods, and even static variables.在 Java 中,您有静态块、静态方法,甚至是静态变量。 Hence it's obvious that you can also have static classes.因此很明显,您也可以拥有静态类。 In Java, it is possible to have a class inside another class and this is called a Nested class.在 Java 中,可以在另一个类中包含一个类,这称为嵌套类。 The class that encloses the nested class is called the Outer class.包含嵌套类的类称为 Outer 类。

In Java, although you can declare a nested class as Static it is not possible to have the outer class as Static.在 Java 中,虽然可以将嵌套类声明为静态,但不能将外部类声明为静态。

Let's now explore the static nested classes in Java.现在让我们探索 Java 中的静态嵌套类。

Static Nested Class静态嵌套类

As already mentioned, you can have a nested class in Java declared as static.如前所述,您可以在 Java 中将嵌套类声明为静态。 The static nested class differs from the non-static nested class(inner class) in certain aspects as listed below.静态嵌套类在某些方面不同于非静态嵌套类(内部类),如下所示。

Unlike the non-static nested class, the nested static class doesn't need an outer class reference.与非静态嵌套类不同,嵌套静态类不需要外部类引用。

A static nested class can access only static members of the outer class as against the non-static classes that can access static as well as non-static members of the outer class.静态嵌套类只能访问外部类的静态成员,而非静态类可以访问外部类的静态成员和非静态成员。

An example of a static nested class is given below.下面给出了一个静态嵌套类的示例。


class Main{
  private static String str = "SoftwareTestingHelp";

     //Static nested class
     static class NestedClass{
        //non-static method
            public void display() {

            System.out.println("Static string in OuterClass: " + str);
            }

    }
   public static void main(String args[])
   {
            Main.NestedClassobj = new Main.NestedClass();
            obj.display();
   }
}

output输出

Static string in OuterClass: SoftwareTestingHelp

I think this is how static keyword works in java.我认为这就是 static 关键字在 java 中的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM