0

The below code is getting compiled without any errors inspite of accessing the method dir from a null object rt, whereas i was expected to get nullpointerexception. Why?

When i removed the static keyword for dir method, i got the null pointer exception, so is there any exception for static methods?

public class root{

  private root() {}

   final public static void dir(int a)
    {
      System.out.print("Output: "+a);
    }
  }

public class plan{

  public root rt=null;

  public void plot(){ 
       rt.dir(1); //Calling a static method using null object
    }

  public void static main(String[] args){
     plan p1=new plan();
     p1.plot();
 }
}
Vignesh Paramasivam
  • 2,360
  • 5
  • 26
  • 57

2 Answers2

4

Static methods are not linked with objects. Those are class methods. When you call rt.dir(1), JVM replaces it with Root.dir(1).

It's the instance that can be null and can cause NPE, but not the classes. This is why you cannot see any NullPointerException here.

Kashif Nazar
  • 20,775
  • 5
  • 29
  • 46
-1

If you wish to call static method of another class then you have to write class name while calling static method

You have to use root.dir(1);

Amogh
  • 4,453
  • 11
  • 45
  • 106
  • 2
    Its a good practice to use ClassName, but it is not *mandatory* to use ClassName. He can use an instance of a class to access static members (check his question) – TheLostMind Aug 09 '14 at 09:02