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

前端 未结 11 2085
执念已碎
执念已碎 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:00

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

    Do you mean you have something like:

    public class X
    {
        public void foo()
        {
        }
    }
    

    or do you mean you have something like:

    public class X
    {
        private X()
        {
        }
    
        public void foo()
        {
        }
    }
    

    If it is the fist way then, yes, there is a constructor and it will look like this:

    public X()
    {
        super();
    }
    

    if it is the second way then there is probably a method like:

    public static X createInstance()
    {
        return (new X());
    }
    

    If you really mean can classes have methods that do things without ever creating an instance, then yes you can, just make all of the methods and variables static (usually this is not a good idea, but for some things it is perfect).

    0 讨论(0)
  • 2020-12-15 05:02

    In most languages you can do it only if method is static. And static methods can change only static variables.

    0 讨论(0)
  • 2020-12-15 05:03

    If the methods are static, yes.

    But you won't be able to access non-static members.

    0 讨论(0)
  • 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));
       }
    }
    
    0 讨论(0)
  • 2020-12-15 05:07

    It's called static variables and static methods. Just try it and see that it compiles.

    0 讨论(0)
提交回复
热议问题