static
members (static
fields or static
methods) in Java are associated with their respective class rather than the objects of this class. The following code attempts to access a static field on a null
reference.
public class Main
{
private static final int value = 10;
public Main getNull()
{
return null;
}
public static void main(String[] args)
{
Main main=new Main();
System.out.println("value = "+main.getNull().value);
}
}
Although main.getNull()
returns null
, it works and displays value = 10
. How does this code work?
Main main = null; main.getNull().value
. – Meatusnew Thread[]{}[-1].sleep(10);
where sleep() is a static method. This used to succeed on some older Java versions. – Strawworm