Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call static method on null object [duplicate]

Tags:

java

null

I'm curious to know how would you explain this task I found in this quiz? Even when the getFoo method returns null, the output is still Getting Object JavaQuiz . I think it should be NullPointerException.

   public class Foo {

        static String name = " JavaQuiz";

        static Foo getFoo() {
            System.out.print("Getting Object");
            return null;
        }

        public static void main(String[] args) {
            System.out.println(getFoo().name);
        }

   }
like image 299
rozerro Avatar asked Apr 03 '16 07:04

rozerro


2 Answers

Accessing a static method or variable can be done via a null reference for the class that contains that static method/variable.

Since name is static, getFoo().name has the same result as Foo.name or just name, regardless of whether or not getFoo() returns null.

However, it is always better to use the class name when accessing a static method/variable, since it makes it clear that you intended to access a static member.

like image 124
Eran Avatar answered Sep 30 '22 03:09

Eran


static members of a class are class level Members its means there is no need of Object to access these static Members.`

It automatically loaded when classloader of jvm loads the class. So here in this case

static String name = " JavaQuiz"; //load when class get loaded by JVM class loader.

This static variable will exists in memory just after class Foo is getting loaded into the jvm.

static Foo getFoo() {  //method is also a static Member automatically loaded at Class Loading.
            System.out.print("Getting Object");
            return null;
        }

And same will be applied with this static method getFoo().

So Here System.out.println(getFoo().name);. Here is a example to abbriviate my Answer

class StaticExample
{
    static String abc ="India";
    public static void main (String[] args) throws java.lang.Exception
    {
        StaticExample obj = null;
        System.out.println("Value is ==>" + obj.abc + StaticExample.abc + abc);
    }
}

Output:-

 Value is ==>IndiaIndiaIndia

here this line of code will also produce the output.

     System.out.println(((Ideone)null).abc); // this will also print India.

Output:-

 Value is ==>India

Note:- I think there is confusion about getFoo() method but if .name makes a ambiguity. name is a static member so it can access using either className or any null reference . So, Here you may assume this scenario such that this name variable is accessed with any null reference .

Hope you Got the point.

like image 45
Vikrant Kashyap Avatar answered Sep 30 '22 02:09

Vikrant Kashyap