Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

mock test question...pls explain

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class AQuestion
{
private int i=giveMeJ();
private int j=10;

AQuestion()
{
System.out.println("In default cons");
}

private int giveMeJ()
{
System.out.println("In giveMeJ");
return j;
}

public static void main(String []args)
{
System.out.println((new AQuestion()).i);
}
}
Ans In giveMeJ
In default cons
0

I couldn't understand the ans. Before creating an instance we are able to access a non static member function....
 
Ranch Hand
Posts: 218
VI Editor Ruby Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you start instantiating the object, it somewhat existed already .. it just not return yet to you. Probably the confusion is caused by the default value initialization of the atributes using giveMeJ() and value 10 for j, as it seems like they exist outside of the constructor.

As you know everytime you instantiate something, VM create the object instant and setup the attribute area first where object get null and primitive get the 0 value or false for boolean, then it call the constructor.

When you set it with your own default value, the compiler actually move them into your constructor. So the code you wrote is no difference than this:


You can see it happen in the bytecode that is generated by your code and the above code.



And BQuestion bycode:


Hope that helps
 
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Wirianto Djunaidi,

Thanks for such a great explanation of the concept. It is really very useful to understand. And your explanation with the bytecode is excellent. I have never thought of something like this in these terms.

Thanks
Kaps
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic