• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why output of this code showing different value?  RSS feed

 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have one code [taking from on line SCJP exam preparation site]. Can someone explain to me this?

I have 2 question in my mind:

1) addValue() is non static method then why it is running without object inside constructor. By this rule it should show compilation error.
2) With ref variable of parent always non overridden methods of parent run then it must value of 10 [If i forgot 1st point ]


But it is giving 40. Code is as below:

 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tushar Goel wrote: . . . non static method then why it is running without object inside constructor. . . .
A constructor always runs inside an instance. You can therefore always call an instance method from inside the constructor without a compiler error.

Say subclass/superclass not parent/child.
Good design: mark any methods called from inside the constructor private or final or both, to avoid surprises if the method is overridden in subclasses. That code example does not follow such good design. You will doubtless know that exam questions often use bad design in the hope of confusing the reader, and this question appears to have succeeded in that respect

I presume you already know the sequence of events whenever an object is created: remind yourself in the Java Language Specification. You may have to scroll up and down from that link. What you have to do to solve that question is to print the code on a piece of paper (plus public Object()), and get a soft pencil and follow the sequence of events with your pencil. Whenever you get a method call, work out which version of the method (overridden or overriding) you are calling. Then you should easily be able to work out why you are getting 40.
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks Campbell... I just forgot 2 basic principal:

1) calling/using non static data member and member function inside static method

2) construction inheritance using implicit super().

I know these principals but somehow i forgot this...

Anyhow i have learnt 2 things .. JLS link you shared i will definitely read it.. and 2nd your approach to pen down and try it. Thanks again...
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!