File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Gimme the reason for null in o/p Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Gimme the reason for null in o/p" Watch "Gimme the reason for null in o/p" New topic

Gimme the reason for null in o/p

Amit Das
Ranch Hand

Joined: Mar 05, 2005
Posts: 206
Hi all,

I have a piece of code. Plz tell me tht after running the code why its giving one of the o/ps as null
Put this snnipet in file.

class Phone
String device = "Phone.device";
void showDevice()
System.out.print("Phone.showDevice," + device + " ");


public class Mobile extends Phone
String device = "Mobile.device";
void showDevice()
System.out.print("Mobile.showDevice," + device + " ");


public static void main(String[] args)
Mobile n = new Mobile();

//The o/p is:hereunder
//Mobile.showDevice,null Mobile.showDevice,Mobile.device Mobile.showDevice,Mobile.device

Thanks & Regards,

Amit Kumar Das
Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
Using code tags for ur code

Ok what happens here is:
1) before the mobile constructor runs, the super class constructor is called and when it happens the instance variable are still in the uninitialized state.
2) U can see that during super class constructor call u have showDevice() method called. Now this showDevice() method will be called for the Mobile object. This is becuase as u know method is called based on the object, so here the object is Mobile, so its method is called.
3) Now since ur variable "device" is still not initialized, its considered to be null.
Thats why ur output consists of null

After the super class constructor completes its running, the subclass constructor is run and thus the variable gets initialized.

Hope this makes u clear
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Gimme the reason for null in o/p
Similar Threads
Interface Q
Parent constructor calls method of Child
Overloading,Overriding, Runtime Type
Constructor doubt