aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help how its working Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Help how its working" Watch "Help how its working" New topic
Author

Help how its working

deep_scjp
Greenhorn

Joined: Jan 04, 2001
Posts: 12
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


Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
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

Joined: Jan 04, 2001
Posts: 12
thnx Anshuman
i got your answer,
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
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.


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help how its working
 
Similar Threads
what is wrong ?
compile-time errror
A question on constructor
Constructors
A classic java problem. Why?