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

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

问题描述

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

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所指出的,不是在Math类的情况下)。

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中的Static修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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