aspose file tools*
The moose likes Beginning Java and the fly likes Runtime Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Runtime" Watch "Runtime" New topic
Author

Runtime

Arnb Sen
Ranch Hand

Joined: Feb 23, 2004
Posts: 145


Output is

2
class2.test()

Can someone please explain ? I can understand the reason for the first one.


Regards,<br />Arnab
Arnb Sen
Ranch Hand

Joined: Feb 23, 2004
Posts: 145
Also, how is the output for this code



is

class4.test() <<-- Cannot understand this output
2
class4.test()
Sanjaya Sugiarto
Ranch Hand

Joined: Mar 25, 2004
Posts: 229
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()


<a href="http://www.wi.hs-furtwangen.de" target="_blank" rel="nofollow">Business Information Technology - Hochschule Furtwangen University, Germany</a>
soudamini.s shirkhedkar
Greenhorn

Joined: Nov 29, 2005
Posts: 9
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

Joined: Aug 30, 2005
Posts: 10

Clean answer!
Thanks!
[ December 01, 2005: Message edited by: Benjamin Lau ]

Live for living.<br />Live a life as I wish.
Arnb Sen
Ranch Hand

Joined: Feb 23, 2004
Posts: 145
Thanks
 
 
subject: Runtime