“静态”是什么意思? 关键字在类中做什么?

发布于 2024-07-11 00:26:36 字数 431 浏览 7 评论 0原文

具体来说,我正在尝试这段代码:

package hello;

public class Hello {

    Clock clock = new Clock();

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

但它给出了错误

无法在静态方法main中访问非静态字段

所以我将 clock 的声明更改为:

static Clock clock = new Clock();

它起作用了。 将关键字放在声明之前是什么意思? 它到底会做什么和/或限制对该对象可以做什么?

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

So I changed the declaration of clock to this:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

莫多说 2024-07-18 00:26:37

还可以认为静态成员没有“this”指针。 它们在所有实例之间共享。

Can also think of static members not having a "this" pointer. They are shared among all instances.

故事和酒 2024-07-18 00:26:37

理解静态概念

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 */

    }
}

第二课

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

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

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");
    }
}
一人独醉 2024-07-18 00:26:37

此处提出了关于为此选择“静态”一词的问题概念。 这是对这个问题的重复,但我认为词源尚未得到明确解决。 所以...


这是由于关键字重用,从 C 开始。

考虑 C 中的数据声明(在函数体内):

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

变量 foo 在函数进入时在堆栈上创建(并在函数终止时销毁)。 相比之下,bar 总是在那里,所以从普通英语的意义上来说它是“静态的”——它不会去任何地方。

Java 和类似的语言对于数据具有相同的概念。 可以为每个类的实例(每个对象)分配数据,也可以为整个类分配一次数据。 由于 Java 的目标是让 C/C++ 程序员熟悉语法,因此“static”关键字在这里是合适的。

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

最后,我们来谈谈方法。

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

从概念上讲,C 类的每个实例都有一个 foo() 实例。整个 C 类只有一个 bar() 实例。这与我们讨论的数据情况类似,因此使用“static” ' 又是一个明智的选择,特别是如果您不想在您的语言中添加更多保留关键字。

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.

Consider data declarations in C (inside a function body):

    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). By contrast, bar is always there, so it's 'static' in the sense of common English - it's not going anywhere.

Java, and similar languages, have the same concept for data. 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.

    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.

心如荒岛 2024-07-18 00:26:37

main() 是一个静态方法,它有两个基本限制:

  1. 静态方法不能使用非静态数据成员或直接调用非静态方法。

  2. this()super() 不能在静态上下文中使用。

    <前><代码>A类{
    整数a=40; //非静态
    公共静态无效主(字符串参数[]){
    System.out.println(a);
    }
    }

输出:

Compile Time Error

main() is a static method which has two fundamental restrictions:

  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.

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

Output:

Compile Time Error
一枫情书 2024-07-18 00:26:37

静态变量只能在静态方法中访问,因此当我们声明静态变量时,那些 getter 和 setter 方法将是静态方法

静态方法是类级别,我们可以使用类名访问

以下是静态变量 Getters 和 Setters 的示例:

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;
    }

}

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

static methods is a class level we can access using class name

The following is example for Static Variables Getters And Setters:

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;
    }

}
九八野马 2024-07-18 00:26:37

Java 程序中的成员可以在声明/定义之前使用关键字“static”来声明为静态成员。 当一个成员被声明为静态时,它本质上意味着该成员由类的所有实例共享,而无需为每个实例创建副本。

因此 static 是 Java 中使用的非类修饰符,可应用于以下成员:

  • 变量
  • 方法
  • 类(更具体地说,嵌套类)

当成员声明为 static 时,就可以访问它不使用对象。 这意味着在实例化类之前,静态成员是活动的且可访问的。 与当类的对象超出范围时不再存在的其他非静态类成员不同,静态成员显然仍然是活动的。

Java中的静态变量

声明为静态的类的成员变量称为静态变量。 它也被称为“类变量”。 一旦变量被声明为静态,则在实例化类时仅分配一次内存,而不是每次都分配内存。 因此,您可以访问静态变量而无需引用对象。

下面的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);
   }
 }

输出::

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

在上面的程序中,我们有两个静态变量,即a和b。 我们在函数“printStatic”和“main”中修改这些变量。 请注意,即使函数的作用域结束,这些静态变量的值也会在函数中保留。 输出显示两个函数中变量的值。

静态方法

Java中的方法是静态的,当它前面有关键字“static”时。

关于静态方法,您需要记住的一些要点包括:

  • 与其他非静态方法相比,静态方法属于该类
    使用类的实例调用的方法。
  • 要调用静态方法,不需要类对象。
  • 类的静态数据成员可以被静态访问
    方法。 静态方法甚至可以改变静态的值
    数据成员。
  • 静态方法不能引用“this”或“super”成员。
    即使静态方法尝试引用它们,它也将是编译器
    错误。
  • 就像静态数据一样,静态方法也可以调用其他静态方法
    方法。 静态方法不能引用非静态数据成员或
    变量也不能调用非静态方法。

下面的程序展示了 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();
   }
 }

输出:

Static method in Java...called without any object

Java 中的静态块

就像编程语言中的功能块一样C++、C#等在Java中也有一个特殊的块,称为“静态”块,通常包含与静态数据相关的代码块。

该静态块在创建类的第一个对象时(恰好在类加载时)或使用块内的静态成员时执行。

下面的程序展示了静态块的用法。

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);
  }
}

输出:

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

静态类

在 Java 中,有静态块、静态方法,甚至静态变量。 因此,很明显您也可以拥有静态类。 在Java中,一个类可以包含在另一个类中,这称为嵌套类。 包含嵌套类的类称为外部类。

在 Java 中,虽然可以将嵌套类声明为 Static,但不可能将外部类声明为 Static。

现在让我们探索一下 Java 中的静态嵌套类。

静态嵌套类

正如已经提到的,您可以将 Java 中的嵌套类声明为静态。 静态嵌套类与非静态嵌套类(内部类)在某些方面有所不同,如下所列。

与非静态嵌套类不同,嵌套静态类不需要外部类引用。

静态嵌套类只能访问外部类的静态成员,而非静态类可以访问外部类的静态成员和非静态成员。

下面给出了静态嵌套类的示例。


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();
   }
}

输出

Static string in OuterClass: SoftwareTestingHelp

我认为这就是静态关键字在java中的工作原理。

A member in a Java program can be declared as static using the keyword “static” preceding its declaration/definition. 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:

  • 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

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:

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 i.e. a and b. We modify these variables in a function “printStatic” as well as in “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”.

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.
    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:

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

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.

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. 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. The class that encloses the nested class is called the Outer class.

In Java, although you can declare a nested class as Static it is not possible to have the outer class as Static.

Let’s now explore the static nested classes in Java.

Static Nested Class

As already mentioned, you can have a nested class in Java declared as static. 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.

难忘№最初的完美 2024-07-18 00:26:36

static 成员属于类而不是特定实例。

这意味着只有一个 static 字段存在[1],即使您创建了该类的一百万个实例,或者您不这样做创建任何。 它将被所有实例共享。

由于静态方法也不属于特定实例,因此它们无法引用实例成员。 在给出的示例中,main 不知道它应该引用 Hello 类的哪个实例(因此也不知道 Clock 类的哪个实例) 。 static 成员只能引用static 成员。 当然,实例成员可以访问静态成员。

附注:当然,静态成员可以通过对象引用访问实例成员。

示例:

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]:根据运行时特性,它可以是每个 ClassLoader 或 AppDomain 或线程一个,但这不是重点。

static members belong to the class instead of a specific instance.

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. 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. 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. static members can only refer to static members. Instance members can, of course access static members.

Side note: Of course, static members can access instance members through an object reference.

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.

仙女山的月亮 2024-07-18 00:26:36

这意味着 Hello 中只有一个“clock”实例,而不是“Hello”类的每个单独实例都有一个实例,或者更重要的是,这意味着在 Hello 类的所有实例中将有一个共同共享的“clock”引用“你好”课程。

因此,如果您要在代码中的任何位置执行“new Hello”:
A-在第一个场景中(在更改之前,不使用“static”),每次调用“new Hello”时都会创建一个新时钟,但是
B-在第二种情况下(更改后,使用“静态”),每个“新Hello”实例仍将共享并使用最初创建的初始且相同的“时钟”引用。

除非你需要 main 之外的某个地方的“时钟”,否则这也同样有效:

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

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.

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.

Unless you needed "clock" somewhere outside of main, this would work just as well:

package hello;
public class Hello
{
    public static void main(String args[])
    {
      Clock clock=new Clock();
      clock.sayTime();    
    }
}
夏の忆 2024-07-18 00:26:36

static 关键字意味着某些内容(字段、方法或嵌套类)与类型相关,而不是与该类型的任何特定实例相关。 例如,在没有任何 Math 类实例的情况下调用 Math.sin(...) ,实际上您无法创建Math 类的实例。

有关详细信息,请参阅 Oracle Java 教程的相关内容


旁注

不幸的是,Java允许您访问静态成员,就好像它们是实例成员一样,例如,

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

这使得它看起来就像睡眠 是一个实例方法,但它实际上是一个静态方法 - 它总是使当前线程休眠。 更好的做法是在调用代码中明确这一点:

// Clearer
Thread.sleep(5000);

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. 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.

For more information, see the relevant bit of Oracle's Java Tutorial.


Sidenote

Java unfortunately allows you to access static members as if they were instance members, e.g.

// 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. It's better practice to make this clear in the calling code:

// Clearer
Thread.sleep(5000);
终难遇 2024-07-18 00:26:36

Java 中的static 关键字意味着变量或函数在该类的所有实例之间共享,因为它属于类型,而不是实际的对象本身。

因此,如果您有一个变量:private static int i = 0;,并且在一个实例中递增它 (i++),则更改将反映在所有实例中。 i 现在在所有情况下都将为 1。

无需实例化对象即可使用静态方法。

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.

So if you have a variable: private static int i = 0; and you increment it (i++) in one instance, the change will be reflected in all instances. i will now be 1 in all instances.

Static methods can be used without instantiating an object.

多情出卖 2024-07-18 00:26:36

静态成员的基本用法...

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
}

这就是如何在所有类成员中共享值,而无需向其他类发送类实例 Hello 的方法。 而且静态的你不需要创建类实例。

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

您可以只通过类名调用静态值或方法:

Hello.staticValue = "abc";

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. 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";
葬シ愛 2024-07-18 00:26:36

静态意味着您不必创建类的实例即可使用与该类关联的方法或变量。 在您的示例中,您可以

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

直接调用:,而不是:

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

从静态方法(属于类)内部,您无法访问任何非静态成员,因为它们的值取决于您对类的实例化。 作为实例成员的非静态 Clock 对象对于 Hello 类的每个实例都有不同的值/引用,因此您无法从类的静态部分访问它。

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.

魄砕の薆 2024-07-18 00:26:36

Java 中的静态

静态是一种非访问修饰符。
static 关键字属于类而不是类的实例。
可用于将变量或方法附加到类。

静态关键字可以用于:

中的方法

变量

嵌套在另一个类

初始化块

不能用于:

类(非嵌套)

构造函数

接口

方法局部内部类(差异)然后嵌套类)

内部类方法

实例变量

局部变量

示例:

想象一下以下示例,其中有一个名为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();

    }
}

输出:

1 1 1

由于实例变量在对象创建时获取内存,因此每个对象都会拥有实例变量的副本,如果它递增,则不会反映到其他对象。

现在,如果我们将实例变量计数更改为静态,那么程序将产生不同的输出:

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();

    }
}

输出:

1 2 3

在这种情况下,静态变量只会获得一次内存,如果任何对象更改了静态变量的值,它将保留其值。

Static with Final:

声明为final and static的全局变量在整个执行过程中保持不变。 因为,静态成员存储在类内存中,并且在整个执行过程中仅加载一次。 它们对于该类的所有对象都是通用的。 如果将静态变量声明为final,则任何对象都无法更改其值,因为它是final的。 因此,声明为final和static的变量有时被称为常量。 接口的所有字段都称为常量,因为它们默认是最终的和静态的。

输入图片描述这里

图片资源:最终静态

Static in Java:

Static is a Non Access Modifier.
The static keyword belongs to the class than instance of the class.
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:

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

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:

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

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. 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. Therefore, variables declared as final and static are sometimes referred to as Constants. All fields of interfaces are referred as constants, because they are final and static by default.

enter image description here

Picture Resource : Final Static

小苏打饼 2024-07-18 00:26:36

为了补充现有的答案,让我尝试用一​​张图片:

所有储蓄账户都适用 2% 的利率。 因此它是静态的

余额应该是单独的,因此它不是静态的。

输入图像描述这里

To add to existing answers, let me try with a picture:

An interest rate of 2% is applied to ALL savings accounts. Hence it is static.

A balance should be individual, so it is not static.

enter image description here

聆听风音 2024-07-18 00:26:36

到目前为止,这个讨论忽略了类加载器的考虑。 严格来说,Java 静态字段在给定类加载器的所有类实例之间共享。

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.

菊凝晚露 2024-07-18 00:26:36

字段可以分配给类或类的实例。 默认情况下,字段是实例变量。 通过使用static,该字段成为一个类变量,因此只有一个时钟。 如果您在一处进行更改,则它在任何地方都可见。 实例变量的更改是相互独立的。

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. If you make a changes in one place, it's visible everywhere. Instance varables are changed independently of one another.

剪不断理还乱 2024-07-18 00:26:36

在Java中,static关键字可以简单地看作表示以下内容:

“不考虑或与任何特定实例无关”

如果您以这种方式思考 static,就会更容易理解它在遇到它的各种上下文中的用法:

  • A static 字段是属于类而不是任何特定实例的字段

  • 静态方法是没有this概念的方法; 它是在类上定义的,并且不知道该类的任何特定实例,除非将引用传递给它

  • static 成员类是一个嵌套类,没有任何概念或知识其封闭类的实例(除非将对其封闭类实例的引用传递给它)

In Java, the static keyword can be simply regarded as indicating the following:

"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:

  • A static field is a field that belongs to the class rather than to any particular instance

  • A static method is a method that has no notion of 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)

你的他你的她 2024-07-18 00:26:36

关键字static用于表示字段或方法属于类本身而不是任何特定实例。 使用您的代码,如果对象 Clock 是静态的,则 Hello 类的所有实例将共享此 Clock 数据成员(字段)常见的。 如果将其设置为非静态,则 Hello 的每个单独实例都将具有唯一的 Clock

您向类 Hello 添加了一个 main 方法,以便可以运行代码。 问题是 main 方法是静态的,因此它不能引用其中的非静态字段或方法。 您可以通过两种方式解决此问题:

  1. Hello 类的所有字段和方法设为静态,以便可以在 main 方法中引用它们。 这不是一件好事(或者使字段和/或方法静态化的错误原因)
  2. 在 main 方法中创建 Hello 类的实例并访问其所有字段和方法它们最初的访问和使用方式。

对于您来说,这意味着对您的代码进行以下更改:

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();
    }
}

The keyword static is used to denote a field or a method as belonging to the class itself and not to any particular instance. 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. If you make it non-static, each individual instance of Hello will have a unique Clock.

You added a main method to your class Hello so that you could run the code. 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. 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. This is 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 its fields and methods the way they were intended to be accessed and used in the first place.

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();
    }
}
爱情眠于流年 2024-07-18 00:26:36

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

static methods don't use any instance variables of the class they are defined in. A very good explanation of the difference can be found on this page

不如归去 2024-07-18 00:26:36

我已经开始喜欢“helper”类中的静态方法(仅在可能的情况下)。

调用类不需要创建辅助类的另一个成员(实例)变量。 您只需调用辅助类的方法即可。 此外,辅助类也得到了改进,因为您不再需要构造函数,并且不需要成员(实例)变量。

可能还有其他优点。

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.

清君侧 2024-07-18 00:26:36

静态使时钟成员成为类成员而不是实例成员。 如果没有 static 关键字,您将需要创建 Hello 类的实例(它有一个时钟成员变量) - 例如

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

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) - e.g.

Hello hello = new Hello();
hello.clock.sayTime();
对你再特殊 2024-07-18 00:26:36
//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
    }
}
//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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文