I am new to java and I have some problem on Casting.
I have a class called Parent, and a class called Children, the Children class is the subclass of Parent.
public class Parent
{
int age;
String occupation;
public void print()
{
System.out.println("My age is:"+ age + "and i am a:" + occupation);
}
}
public class Children extends Parent
{
int height;
public static void main(String args[])
{
Children c = new Children();
Parent p = new Parent();
p=c;
c=(Children) p;
/**Here***/
}
}
My problem is, when I add p.XXX after the casting, I only see the age and occupation accessible for instance p. and when I do c.xxx, I see all age, occupation and height accessible.
I thought when I do p=c, p now are considered to be an instance of a children class isn’t it? If yes, then why i didnt see the height integer accessible?
And when I do c=(Children)p, an instance of Parent class is assigned to an instance of Children class, and since the Parent instance doesn’t have a option, that why we do a casting from parent to children, correct?
No. The type of the variable
pis stillParent. The value will be a reference to an instance ofChildren, but the compiler doesn’t take that into account. It only uses the declared type of the variable.Well you’re not changing the instance at all. You’re casting an expression of type
Parent– the value will be a reference. At execution time, the JVM will ensure that the value is actually a reference to an instance ofChildrenor some subtype (or null) – if it isn’t, the JVM will throw an exception.It’s very important to distinguish between variables, references and objects – they’re three quite different concepts, and making sure you understand the difference between them will make a lot of other things clearer.