34

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
Roman
  • 124,451
  • 167
  • 349
  • 456

13 Answers13

33

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

Yoni
  • 10,171
  • 9
  • 55
  • 72
14

If the methods are static, yes.

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

µBio
  • 10,668
  • 6
  • 38
  • 56
13

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

Martin
  • 2,411
  • 11
  • 28
  • 30
Aviral Kumar
  • 131
  • 1
  • 3
9

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.

pmr
  • 58,701
  • 10
  • 113
  • 156
3

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

user272879
  • 61
  • 1
3

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

If you don't explicitly define a constructor then you get a default constructor provided by the compiler. So if those methods aren't static, try this:

NameOfClass x = new NameOfClass();
x.doMethod(x1,x2,...,xn);
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
3

A method on a class operates in the context an instance; it has access to the instance's member variables. You understand this, because you ask about what happens if the method accesses one of those variables.

You can understand why it doesn't work by asking yourself the question: "Where is the data?" If you don't have an instance, where is the instance variable? Where is the data? And the answer is that it doesn't have a place and therefore doesn't work.

The difference with a static function and static member variables is that you can answer the question about the location of the data. The static variables available regardless of whether there is a specific instance or not. The instance specific vs. class specific decision is one that you must make considering what you actually want to do.

janm
  • 17,976
  • 1
  • 43
  • 61
2

That would be static methods.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
1

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).

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
0

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));
   }
}
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
0

In proper encapsulation, you should not "see" what is happening upon instanciation. To rely on a class's lack of a constructor is breaking this form. The designed of the class my have in mind to add formal state initialization in the constructor at a later date. Your "contract" with the class is only that you can use the methods as they are currently designed.

If you desire to use the functionality of that method without the class overhead, maybe it best for you to include that method in your existing "client" class (of course this is just "copy and paste" coding and is considered an anti-pattern of of software design.

0

If you are using lombok, here is what you can do:

package util;
import lombok.experimental.UtilityClass;

@UtilityClass
public class UtilFunctions {
    public static int SumOfTwoNumber(int a, int b){
        return a+b;
    }
}

In UtilFunctions class here with @UtilityClass annotation, you can keep all the functions which you want to call anywhere in your project. For the sake of simplicity, I have created a function SumOfTwoNumber which I want to use in my main class. Here is how I can call it in the main class:

import util.UtilFunctions;

public class HeadFirstJavaApplication {
    public static void main(String[] args) {
        int a = 10, b = 20;
        int sum = UtilFunctions.SumOfTwoNumber(a,b);
        System.out.println(sum);
    }
}

P.S: Don't forget to add lombok dependency to be able to use it. In case of gradle, here is how to add the lombok dependency:

dependencies {
     compileOnly 'org.projectlombok:lombok:1.18.16'
     annotationProcessor 'org.projectlombok:lombok:1.18.16'

     testCompileOnly 'org.projectlombok:lombok:1.18.16'
     testAnnotationProcessor 'org.projectlombok:lombok:1.18.16'
}
abhinav1602
  • 1,190
  • 17
  • 18
0

Yes. You cando that, but only Under One Condition. You have to make your method or Variable a static type. How ? Just add a static Key word before them

Now you can use both of them with out creating an object. N.B The static key words gives them the character of global Variable and any change appplies for all objects created from that class