0

How null reference to an object can invoke static method. Here is the sample code

class A{
public static void show(){
System.out.println("In Show");
}
psvm(..)
{
A a = null;
a.show();
}

Here as an output "In Show" is printed. I was expecting NPE . Request an understanding

Abhishek Saxena
  • 292
  • 3
  • 15
  • There is no need for an instance while invoking static member or method. Since static members belongs to class rather than instance. – Suresh Atta Aug 14 '15 at 08:42
  • @suresh agreed but we explicity assigned null to the reference – Abhishek Saxena Aug 14 '15 at 08:42
  • 1
    you are talking about the value of instance. I am telling that type of instance enough. – Suresh Atta Aug 14 '15 at 08:43
  • 1
    @Abhishek you'll also find it doesn't matter what that objects real type is (e.g. A child class) all that matters is the declared type. Really static methods shouldn't ever be called on instances like this – Richard Tingle Aug 14 '15 at 09:43

1 Answers1

1

Because you're really calling A.show(), since the method is static. It doesn't really need the instance a.

Trisha
  • 3,891
  • 1
  • 25
  • 39