在 Java 中如何以及在何处使用静态修饰符? [英] How and where to use Static modifier in Java?

查看:25
本文介绍了在 Java 中如何以及在何处使用静态修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们应该如何以及在何处使用静态修饰符:

How and where should we use a Static modifier for:

1.字段和
2. 方法?

对于示例java.lang.Math 类,abs()、atan()、cos() 等字段方法是静态的,即它们可以通过以下方式访问:Math.abs()

For example in java.lang.Math class, the fields methods like abs(), atan(), cos() etc are static, i.e. they can be accessed as: Math.abs()

但为什么这是一个好的做法?

But why is it a good practice?

说,我不让它保持静态并创建类的对象并访问它,无论如何我可以,我只会收到警告,您正在尝试以非静态方式访问静态方法(正如@duffymo 所指出的,不是在数学课的情况下).

Say, I don't keep it static and create an object of the class and access it, which anyways I can, I will just get a warning that, you are trying to access a static method in a non static way (as pointed out by @duffymo, not in case of Math class).

更新 1:

因此,实用方法应该是静态的,即其工作仅依赖于方法参数.因此,例如,方法 updateString(String inputQuery, String highlightDoc) 是否应该是 这个问题?

So, utility method, should be static, i.e. whose work is only dependent on the method parameters. So, for example, can the method updateString(String inputQuery, String highlightDoc) should have been a static method in this question?

推荐答案

您可以将静态"方法或字段视为在类定义之外声明的.换句话说

You can think of a 'static' method or field as if it were declared outside the class definition. In other words

  1. 静态字段/方法只有一个副本".
  2. 静态字段/方法无法访问非静态字段/方法.

在某些情况下,您可能希望将某些内容设为静态.

There are several instances where you would want to make something static.

字段的规范示例是创建一个静态整数字段,该字段保持一个类的所有实例(对象)的计数.此外,例如,单例对象通常也使用静态修饰符.

The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.

同样,静态方法可用于执行实用"作业,其中所有必需的依赖项都作为参数传递给方法 - 您不能在静态方法中引用this"关键字.

Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.

在 C# 中,您也可以拥有静态类,正如您可能猜到的那样,它们只包含静态成员:

In C#, you can also have static classes which, as you might guess, contain only static members:

public static class MyContainer
{
    private static int _myStatic;

    public static void PrintMe(string someString)
    {
        Console.Out.WriteLine(someString);
        _myStatic++;
    }

    public static int PrintedInstances()
    {
        return _myStatic;
    }
}

这篇关于在 Java 中如何以及在何处使用静态修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆