aspose file tools*
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
Author

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 Mobile.java file.


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

Phone()
{
showDevice();
}
}

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

Mobile()
{
showDevice();
}

public static void main(String[] args)
{
Mobile n = new Mobile();
n.showDevice();
}
}

//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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Gimme the reason for null in o/p