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

91,897

Solution 1

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

Solution 2

If the methods are static, yes.

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

Solution 3

1) YES, you can use the methods of a class without creating an instance or object of that class through the use of the Keyword "Static".

2) If you declare the method as "Static" then you can call this method by :

                *ClassName.MethodName()* 

3) E.g.

class Hello {

   public static void print()
   {

     System.out.println("HelloStatic");
   }  

}


class MainMethod {
    public static void main(String args[])
    {
       // calling static method
       Hello.print();
    } 
}  

4) The output of the above program would be : HelloStatic

Solution 4

As many have pointed out: This is only possible if the method is static. Maybe some OOP background is in order: A method should always belong to a class. So what is the use of calling a method without an instance of a class? In a perfect OO world there shouldn't be any reason to do that. A lot of use cases that have to do with static methods talk about assigning some kind of identity to your class. While this is perfectly reasonable in a programming world it isn't very convincing when it comes to object oriented design.

As we program in an imperfect world there is often a use case for a "free function" (The way Java or C++ implement sort() for example). As Java has no direct support for free functions classes with only static "methods" are used to express those semantics with the added benefit of the class wrapper providing a "namespace". What you think of this workaround and if you see it as a flaw in language design is IMO a matter of opinion.

Solution 5

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

Share:
91,897
Roman
Author by

Roman

Updated on July 10, 2022

Comments

  • Roman
    Roman almost 2 years

    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 creation of an instance of the class.

    For example, I can do something like that:

    NameOfClass.doMethod(x1,x2,...,xn)
    

    In general I do not see why it should be impossible. I just call a function which does something (or return some values). If it is possible, what will happen if the method sets a value for a private variable of the class. How can I reach this value? In the same way?

    NameOfClass.nameOfVariable