I have following sample code explaining sample Polymorphism concept – Overriding
class Super
{
public int number = 1;
public char superText='a';
public String getColor()
{
return "red";
}
}
class Sub extends Super
{
public int number = 2;
public char subText='b';
public String getColor()
{
return "blue";
}
}
public class Sample2
{
public static void main(String[] args)
{
Super supersub = new Sub();
System.out.println( supersub.getColor() + supersub.number + supersub.superText );
}
}
The Output is blue1.
Question 1:
The Method in derived class getColor() is overridden and Field of the Super class is displayed.
Can some one explain why number field in derived class is not called ? i.e., output is blue2
Question 2: *REGARDING MEMORY ALLOCATION*
for below object instantiation,
Sub subobj = new Sub();
Memory for field ‘number’ is allocated in heap and the address of the Number variable
is assigned to object reference, subobj.
consider below case,
Super supersub = new Sub();
(a) Here memory for variables, ‘number and subText’ in derived class ‘Sub’ is created and the address of the variables is placed in supersub Object
when i access, supersub.subText i got error that subText cannot be resolved.
SO, PLEASE EXPLAIN POINT (a) described above i.e., Memory Allocation of Derive Class variables
Thanks,
Cyborgz
Fields cannot be overridden. Even if two classes share a parent-child relationship, the fields belong to the class they were defined in, even if they share names with an inherited field. In other words,
numberinSubis totally different field thannumberinSuper.The object stored in
supersubis of typeSub, but the compiler doesn’t know that.Because Java is a statically typed language, the compiler goes by the declared type (that is, the variable type) of the reference because, in most real-world cases, the runtime type (the one that’s apparent in the
newexpression) isn’t necessarily known at compile time. For example, you may have gotten this object from another method, or from two or three candidate methods, therefore the runtime type is unpredictable.Storing the reference in a superclass variable means that you intend to use that object as
Superfor a while. The compiler, then, works on this perceived intention of yours.Superisn’t guaranteed to only have instances of a runtime type ofSub, therefore it can’t make the assumptions you expect.That being said, storing the reference in one kind of variable or another does not modify the object. If you were to cast the object back to a variable of a type that actually knows about those members you’re trying to access (in your case, the
Subtype), you’ll find that they’re still there (and they retain their values).