简体   繁体   English

如何在Java中调用静态方法?

[英]How to call a static method in Java?

Here i have a class named FirefoxPhDriver 在这里,我有一个名为FirefoxPhDriver的类

public class FirefoxPhDriver extends AbstractWebPhDriver {

    public static FirefoxPhDriver newInstance(
            PhDriverIngredients ingredients) {
        FirefoxPhDriver pd = new FirefoxPhDriver();

        if (pd.verify(ingredients)) {
            return pd;
        }

        return null;
    }
}

As i new to java am not sure how can i call this newInstance method in another class 由于我是Java新手,因此不确定如何在另一个类中调用此newInstance方法

i tried 我试过了

FirefoxPhDriver drvr = new FirefoxPhDriver(ingrdients)

But am getting the constuctor FirefoxPhDriver is not visible 但是正在获取构造器FirefoxPhDriver不可见

It's just FirefoxPhDriver drvr = FirefoxPhDriver.newIstance(ingrdients) . 只是FirefoxPhDriver drvr = FirefoxPhDriver.newIstance(ingrdients)

(Because newInstance is a static method you don't need to create an instance of FirefoxPhDriver to access the method (so no new FirefoxPhDriver(...) ).) (由于newInstance是静态方法,因此您无需创建FirefoxPhDriver实例即可访问该方法(因此无需new FirefoxPhDriver(...) )。)

只需调用FirefoxPhDriver drv = FirefoxPhDriver.newInstance(ingrdients)

You actually have no Constructor defined in your FirefoxPhDriver class, but the default Constructor . 实际上,您在FirefoxPhDriver类中没有定义构造函数,而是默认的Constructor

But you have a Method defined 但是你定义了一个方法

public static FirefoxPhDriver newInstance(PhDriverIngredients ingredients) 公共静态FirefoxPhDriver newInstance(PhDriverIngredients成分)

This method creates a new Instance of the FirefoxPhDriver class. 此方法创建FirefoxPhDriver类的新实例。

You can use it like that: 您可以这样使用它:

FirefoxPhDriver drvr = FirefoxPhDriver.newInstance(ingredients);

newInstance() method is static method in FirefoxPhDriver class. newInstance()方法是FirefoxPhDriver类中的静态方法。 We can call static members along with Classname. 我们可以将静态成员与Classname一起调用。

Use this: 用这个:

 FirefoxPhDriver.newInstance(ingrdients);

If you want to call methods from other class we should declare those methods as either public or protected or default. 如果要从其他类调用方法,则应将这些方法声明为public或protected或default。 We cannot call Private members from other class. 我们不能叫其他班级的私人成员。

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

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