Field access and Memory Allocation for Objects in Java Polymorphism-Collection of common programming errors

Question 1:

The Method is derived class is displayed 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

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, number in Sub is totally different field than number in Super.

Question 2: 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.

The object stored in supersub is of type Sub, 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 new expression) 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 intent to use that object as Super for a while. The compiler, then, works on this perceived intention of yours. Super isn’t guaranteed to only have instances of a runtime type of Sub, 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 Sub type), you’ll find that they’re still there (and they retain their values).