-5

In class Main we create a reference variable a from class A ,we all know that we not able to use the reference a until we assign it an object ( A a = new A (); ) because a currently does not point to any object so we must not use property and methods of A class

    public class Main {
    public static void main(String[] args) {             
      A a = null;      
         a.x=5 ;       // fine code in compile time    
         a.y=10 ;     // fine code in compile time     
         a.show();   // fine code in compile time       

    } 
}
 class A {       
     int x ;     
     int y ;      
     public void show (){      
         System.out.println("show method");
     }     
 }

a is reference variable not object ,so the reference a not allocated in memory so it must not see the variable x ,y and the method show in A class in compile time my question here why reference a see x ,y and show method in the compile time although the reference a not allocated in memory ?

Alaa Essam
  • 13
  • 4
  • The difference between soft and warm – Andremoniy Oct 13 '17 at 13:41
  • 1
    `static` methods can be accessed by instance variables, and this is a compile-time feature, not a runtime issue, so the NPE doesn't come into play. `a.show()` is the same as `A.show()`, but you should prefer the latter. – GriffeyDog Oct 13 '17 at 13:46
  • To elaborate a bit: `a.show()` is _exactly_ equivalent to `A.show()` in your example. It's weird, but that's Java. – yshavit Oct 13 '17 at 13:49
  • thanks , but why the reference a access x ,y and the show method in compile time? – Alaa Essam Oct 13 '17 at 14:02
  • I don't understand the question, sorry. – yshavit Oct 13 '17 at 15:06
  • a is reference variable not object ,so the reference a not allocated in memory so must not see the variable x ,y and the method show in A class in compile time my question here why reference a see x ,y and show method in the compile time although the reference a not allocated in memory ? i hope to show my problem in clearly – Alaa Essam Oct 13 '17 at 17:25

1 Answers1

-3

the show() method gives you information about the refference itself( about a). Accesing a member of the object through "a" when "a" is not assigned to any object is illegal. show() will only display information regarding the "a" variable. Your show() method being static will run as thanks to your class. It is not bound to your variable

Rares
  • 3
  • 2