首页 > 编程知识 正文

java静态方法调用静态方法,JAVA的静态方法

时间:2023-05-05 23:06:38 阅读:260512 作者:2489

Static Method in Java belongs to the class and not its instances. A static method can access only static variables of class and invoke only static methods of the class.

Java中的静态方法属于该类,而不是其实例。 静态方法只能访问类的静态变量,并且只能调用类的静态方法。

Usually, static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance. For example Collections class.

通常,静态方法是我们希望公开的实用程序方法,供其他类使用,而无需创建实例。 例如Collections类 。

Java Wrapper classes and utility classes contain a lot of static methods. The main() method that is the entry point of a java program itself is a static method.

Java包装器类和实用程序类包含许多静态方法。 作为Java程序本身入口点的main()方法是静态方法。

静态方法示例 (Static Method Example)

Let’s look at a few simple static method examples.

让我们看一些简单的静态方法示例。

public class MathUtils {public static long add(long i, long j) { return i + j;}//static util methodpublic static int addInts(int i, int...js){ int sum = i; for(int x : js) sum+=x; return sum;}} 用Java调用静态方法 (Calling a Static Method in Java)

We can call a static method using ClassName.method. For example;

我们可以使用ClassName.method调用静态方法。 例如;

MathUtils.add(100L, 20L);MathUtils.addInts(1, 2, 3, 4); 何时在Java中创建静态方法 (When to create static methods in java) Static Method doesn’t require instance creation, so it’s generally faster and provides better performance. That’s why utility class methods in Wrapper classes, System class, Collections class are all static methods.

静态方法不需要实例创建,因此它通常更快并且提供更好的性能。 这就是Wrapper类, System类 ,Collections类中的实用程序类方法都是静态方法的原因。 It’s possible to write fluent code when static imports are used. You will see this a lot in testing frameworks such as JUnit and TestNG.

使用静态导入时,可以编写流畅的代码。 您将在诸如JUnit和TestNG的测试框架中看到很多。 When your method only depends on its parameters, object state has no effect on the method behavior. Then you can create the method as static.

当您的方法仅取决于其参数时,对象状态对方法的行为没有影响。 然后,您可以将方法创建为静态方法。

In all other cases, you should be better with the non-static method.

在所有其他情况下,使用非静态方法应该更好。

Java接口静态方法 (Java Interface Static Method)

From Java 8 onwards, we can define static methods in interfaces too. Java interface static method can’t be overridden in the implementation classes. This feature helps us in avoiding undesired results in case of poor implementation in implementation classes. Let’s look into this with a simple example.

从Java 8开始,我们也可以在接口中定义静态方法。 Java接口静态方法不能在实现类中覆盖。 此功能可帮助我们避免在实现类中的实现不佳的情况下出现不良结果。 让我们通过一个简单的示例对此进行研究。

public interface MyData {static boolean isNull(String str) {System.out.println("Interface Null Check");return str == null ? true : "".equals(str) ? true : false;}}

That’s all for a quick introduction of the static method in java.

这就是快速介绍Java中的静态方法的全部内容。

翻译自: https://www.journaldev.com/22394/static-method-in-java

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。