Kannan Thangadurai Kannan Thangadurai - 1 month ago 7
Java Question

Difference between 'Object obj = new Object()' and 'Object obj = null' in static and non static function

I am have the following code

public class Sample {
public static void display(){
System.out.println("Hai Sample");
}
public void displays(){
System.out.println("Hai Sample");
}
}

public class Sample2 {
public static void main(String[] args) {
Sample obj=null;
obj.display();
obj.displays();
}
}


Here, When we use assign null to Sample obj I can access only static method. If I use new operator like
Sample obj= new Sample();
I can access both static and non static method.

Here My question is, How object initialization happens here and How null refers Sample object's static methods and why not non static method

Answer

The difference is that in one case (new Sample()), you have an instance. In the second case (null), you don't.

display is a static method (related to the class, not any instance); displays is an instance method (related to a specific instance). It's a quirk of Java syntax that you're allowed to refer to static fields and methods through something that looks like an instance reference. Since the instance isn't actually used, it's not dereferenced, and so the fact it's null doesn't cause any trouble.

Your code in main is actually this:

public static void main(String[] args) {
    Sample obj=null;
    Sample.display();  // `display` is static, no instance is used
    obj.displays();    // `displays` is non-static, requires an instance
}

When you seem to call display through obj, in fact all the compiler uses the obj variable for is to see what its type is (in this case, Sample). The value of the variable (null or an instance, either way) isn't used at all, and there's no error.

In contrast, calling displays, the obj variable is used both for its type (Sample) and its value, because when calling displays the JVM needs a reference to use as this for the call. Attempting to call an instance method with a null reference is an error.

Comments