简体   繁体   English

Java 中调用方法的三种方式——静态 vs 非静态

[英]Three ways to call a method in Java - Static vs non static

I am trying to figure out different ways to call methods, and during experimenting, I have come up with 3 ways to do something.我试图找出不同的方法来调用方法,在实验过程中,我想出了 3 种方法来做某事。

public static boolean isFoo(int bar) {
    return bar % 2 == 0;
}

//in a driver class:
foo.isFoo(7);

or或者

public static int foo;

public Foo(int foo) {
    this.foo = foo;

public boolean isFoo() {
    return foo % 2 == 0;
}

//in a driver class:
Foo foo = new Foo(4);
System.out.println(foo.isFoo());

or或者

public static int foo;

public Foo(int foo) {
    this.foo = foo;
}

public static int getFoo() {
    return foo;
}

public static boolean isFoo(Foo foo) {
    return foo.getFoo() % 2 == 0;
}


//in a driver class:
Foo foo = new Foo(14);
System.out.println(Foo.isFoo(foo));

Which of these 3 ways are considered static and why?这 3 种方式中的哪一种被认为是静态的,为什么? I'm not sure because they all use the word static, thus I believe that in the driver, I would be referring to all of them in a static context.我不确定,因为它们都使用静态这个词,因此我相信在驱动程序中,我会在静态上下文中指代所有这些。 Are they all static?它们都是静态的吗?

I have attempted googling but none seem to connect to my situation.我尝试过谷歌搜索,但似乎没有一个与我的情况有关。

Thanks for your help.谢谢你的帮助。

You have only 2 static methods, first and third.您只有 2 个静态方法,第一个和第三个。 Second one is instance method.第二个是实例方法。

Coming to your actual question, do not over think.来到你的实际问题,不要想太多。 Keep the most clean and readable way.保持最干净和可读的方式。 Perfect static method I would say here is我会在这里说的完美静态方法是

public static boolean isFoo(int bar) {
    return bar % 2 == 0;
}

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

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