Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Runtime

 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Output is

2
class2.test()

Can someone please explain ? I can understand the reason for the first one.
 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, how is the output for this code



is

class4.test() <<-- Cannot understand this output
2
class4.test()
 
Sanjaya Sugiarto
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Class4Base has a constructor which has a method called test(). A constructor is always run when you use new keyword.

Originally posted by Arnb Sen:
Also, how is the output for this code



is

class4.test() <<-- Cannot understand this output
2
class4.test()
 
soudamini.s shirkhedkar
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Answers to these two questions are related to the concept of dynamic method binding and varible shadowing.
As you can see, base class as well as a derived class, both have a method named test() and an integer variable i.These two classes do not have a non-default constructor. So, a default constructor will be specified for each one of them by the compiler.
Now, when an object b is created using,
class2Base b = new class2()
This has reference type of class2Base and object type if class2. a default constructor of class2 will be called when we create an object using new operator. This default constructor will call the default constructor of the parent class as its first line. The object state is now initialized. The next line of code is:
System.out.println(b.i). Variable shadowing is resolved on the basis of reference type, in this case, reference type is class2Base. So, integer i from base class ( which is initialized to 2 ) will be displayed.
Next line is:
b.test(). This has object type of class2, so overriden test method from class2 will be called and hence the output.
Your second question can be explained in a similar manner.
Concepts of variable shadowing and dynamic method binding are very important and it helps if you get it right once and for all.
Hope this helps.
Cheers!!
[ December 01, 2005: Message edited by: soudamini.s shirkhedkar ]
 
Benjamin Lau
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Clean answer!
Thanks!
[ December 01, 2005: Message edited by: Benjamin Lau ]
 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic