• 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:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Basic doubt

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
I do no how the result is 100 for the following prog. If any one knows please explain. Thanks in advance.
class Parent
{
int i;
Parent()
{
i = 100;
}
}
class Test extends Parent
{
int i;
Test()
{
i = 200;
}
public static void main(String[] args)
{
Parent t = new Test();
System.out.println(t.i);
}
}
--Gandhi
 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi !!
i am not 100% sure , but i think this is the ans:
i tried putting an add method in both Parent & Test , then the Test method is invoked, what it means is :
if u refer variables , then corresponding variables will only be accessed i.e if u say
Parent p = new Test() , & access p.i, where i is a variable
the value in Parent.i is printed not the child &
if u call a method say add which is both Parent & also in Test
and if u write
Parent p = new Test() & if u call
p.add()then the Test add is called.
hope this is clear...
Regards,
Preeti Pathak
 
Ranch Hand
Posts: 396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi raj,
ppathak is absolutely right. the access to member variable is decided by the type of reference. while the function that will be invoked is decided on the basis of the type of Object.
so if u do
Parent p = new Child();
now if u want to access a member variable x which is common in both Parent and Child i.e. p.x
then x will come from the Parent (coz the reference is of type Parent).
but if u try to access acommon function f() i.e. p.f()
then the function in child is invoked because the object p is referring to is of Child type.

regards
deekasha

 
If we don't do the shopping, we won't have anything for dinner. And I've invited this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic