Quote:
as you guys can see class `Employee` extends `Person` thus it will have all it's fields and method right ?
Only if you will do,
Employee e = (Employee)p;
Then, after a cast, you can see Java being printed. Currently, there is no connection between what p is having and what e contains. Even this will work only and only if you created the instance of an
Employee
, like this.
Person p = new Employee();
Employee e = (Employee)p;
e.show();
This is similar to having this,
String a = "One string";
String b = "Second string";
System.out.println(b);
Only to assume this because both are related through type-system, but they are not the same in-memory. You can make them same by linking their references,
String a = "One string";
String b = a;
System.out.println(b);
But this gets confusing and a lot cumbersome when dealing with parents and children in Java. Because not only you need to assign the variables but you also need to properly cast them—and handle the
ClassCastException
. This is what you would get from your code if you would try that cast.
Person p = new Person();
p.setName("Java");
Employee e = new Employee();
e = (Employee)p;
Employee e = (Employee) p;
I recommend that you read this to understand how inheritance works in Java.
Inheritance (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)[
^]