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

前端 未结 11 2082
执念已碎
执念已碎 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).

提交回复
热议问题