Can I use methods of a class without instantiating this class?

前端 未结 11 2088
执念已碎
执念已碎 2020-12-15 04:10

I have a class with several methods and there is no constructor among these methods.

So, I am wondering if it is possible to call a method of a class without a creat

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 05:05

    Since qre is a static method and doesn't have an access to instances of the enclosing class you'll have first to create an instance and then access it. For example:

    public class Foo {
       private int bar;
    
       public static void qre() {
          Foo foo = new Foo();
          foo.bar = 5;
          System.out.println("next bar: " + (++5));
       }
    }
    

提交回复
热议问题