I'm new to Java and I'm trying to understand what would happen when I assign a child class instance to a parent class instance variable by simulating the following program.
public class ConfusionWithInheritance {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
DerievedClass d = new DerievedClass();
BaseClass b = BaseClass.class.cast(d);
BaseClass b1 = new DerievedClass();
b.doSomeJob();
b.printMagic(); //-> Compiler shouted me that it didn't know this method here.
}
}
class BaseClass {
public void doSomeJob() {
System.out.println("Printing Value X");
}
}
class DerievedClass extends BaseClass {
public void doSomeJob() {
System.out.println("Printing Value Y");
}
public void printMagic() {
System.out.println("Printing magic...");
}
}
1) Why am I allowed to assign an instance of a child class to a parent type variable?
2) From this answer, it's explained that since I'm telling the blue print of the class to be - the parent class - it knows only the methods in the parent class. Then why it's printing the value in the method of child class when I'm invoking childInstance.doSomeJob()?