Tutorial :how does the following code work



Question:

Currently I'm trying to invoke it like this:

class Test {      public static void test() {          System.out.println("hi");      }      public static void main(String[] args) {          Test t = null;          t.test();      }  }  

The output of the code is hi


Solution:1

Try Test.test() with the class name before the dot.

Static methods are called on the class itself not instances of the class.


Solution:2

You don't need to instantiate Test for calling a static method. Your main could be look like this:

public static void main(String[] args) {      Test.test();  }  


Solution:3

Static methiods should be invoked with the class name, without the need for creating an instance of the class, as in

ClassName.methodName(args);  

or

methodName(args); // from other static methods of the same class.  

You can also refer to static methods with an object reference like

instanceName.methodName(args)  

but this is discouraged because it does not make it clear that they are class methods.

So in your case:

Test.test();  

or

test();  

from the main method will do.


Solution:4

Try:

Test.test();  


Solution:5

You are in the same class, you can simply call test() from main().


Solution:6

for (Method m : Class.forName ("Test").getDeclaredMethods ()) {     if (Modifier.isStatic (m.getModifiers ()) {        m.invoke (null);     }  }  

just for lulz


Solution:7

The good thing about static methods and static variables is that you do not need an instance of the class to use it.

Normally you would create an instance and call the method

Test myClass = new Text();  myClass.test();  

However with static methods the first line is not necessary, You just need to write the Class name at the start

Test.test();  

However, in static methods you are not able to access any instance variables inside the Test class - unless they are also static!


Solution:8

By the way. The code works fine without any nullpointerexception This code prints hi

I wanted to know what happens internally when a reference is used to invoke a static method.


Solution:9

It works because when invoking a static method using a reference, the reference is not used. The compiler looks at the declared/static/compile-time type of the expression the method is being called on, and uses that type to find the static method.

You gain nothing by calling a static method on a variable, and you can confuse people who think a polymorphic call is occurring.


Solution:10

Call Test.test(). As the main method is static and in the same class so you can also directly call test() too.


Solution:11

class Test {       public static void test() {           System.out.println("hi");       }         public static void main(String[] args) {           Test.test();      }  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »