• 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
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Help how its working

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear friends
This is my first posting in java ranch ,i have problem in follwing code
class Base{
public int i=10;
public int getI()
{
return this.i;
}
}
class Derived1 extends Base
{
public int i=20;
public int getI()
{
return this.i;
}
}
public class Derived {
public static void main(String[] args){
Base b = new Derived1();
System.out.println("b.i"+ b.i );
System.out.println("b.getI()" + b.getI());
}
}

my question is when i print
System.out.println("b.i"+ b.i );
it is printing b.i 10 why becouse i am making object of drived class so it shoul print b.i 20 but when i printing b.getI()
it is printing 20 why ???
please descirbe in detail
thnx


 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
polymorphism is only for overridden non-static methods. fields and static methods don't get overridden, they just get hidden.
from desborough's note:
Fields do not act polymorphically:
- whenever you access a field from outside the class, the declared type of the reference is used rather than the type of the object it refers to.
- regardless of the type of the reference, a method will always access its own fields rather than those of a derived class.
refer to any good book and you'll find the answer
 
deep_scjp
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thnx Anshuman
i got your answer,
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your name "deep_scjp" does not comply with the JavaRanch naming policy. Please choose one that meets the requirements.

------------------
Ajith Kallambella M.
Sun Certified Programmer for the Java�2 Platform.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic