It seems to me that what you are trying to achieve is impossible.
If you create an instance of ExtendClass
, then that instance always has a lineNo
field.
When you explicitly cast or implicitly convert the type ExtendedClass
to ParentClass
, you don't change the actual instance in any way. At runtime, the instance has that lineNo
field ... in all cases. Now the compiler won't let code within the body of the savePage
method see or refer to that field (unless the code first casts the reference back to the type ExtendedClass
), but the field will be there nonetheless.
You are examining the instances using a debugger. A debugger doesn't follow the rules able what fields should be visible. It sees everything, and it shows you everything. And, it clearly shows you the reality ... that the field is really there.
So ... is there a way to make the field go away entirely? Or hide it from the debugger?
Answers: No, and No.
(Warning: this is tangential to the original question, and probably beyond the OP's understanding.)
Should there be a way to make the field go away? From a language design perspective?
Answer: No.
Consider this code as a "thought experiment":
ExtendedClass ec = new ExtendedClass();
ec.lineNo = 42;
ParentClass pc = (ParentClass) ec; // Actually the cast is redundant
ExtendedClass ec2 = (ExtendedClass) pc;
System.err.println("The old line no is " + ec.lineNo);
System.err.println("The new line no is " + ec2.lineNo);
If (hypothetically) casting from ExtendedClass
to ParentClass
actually removed a field, then when you cast back to ExtendedClass
the field value would no longer be there. But what should ec2.lineNo
actually contain? And how could it be different to ec.lineNo
... unless we had actually created a completely new object when we did the type cast(s)?
Thinking it through, if an explicit or implicit type cast created a new object, then you couldn't effectively do polymorphism. Polymorphism depends on being able to operate on a given object from the viewpoints of either its true type or one of its supertypes. If creating that view actually creates a new object ... it simply doesn't work ... unless Java was a pure functional language; i.e. no mutation.
In short, while it might possibly be an attractive idea for a small number of use-cases, this idea would fundamentally break Java as an OO language.