Interviewers loves to trap candidates in inheritance and overridding concepts. So here is the solution. Just copy the code below and you will understand all about it as soon as you run this code. Let me know in case of any confusion. ;)
P.S.:- Be careful for the "**".
public class InheritanceConcept {
public InheritanceConcept() {
System.out.println("Inside Polymorphism Constructor");
}
public static void main(String args[]) {
Parent p = new Parent();
Child c = new Child();
Parent pCast = new Child();
// Child cCast = (Child) new Parent(); //Class Cast Exception **Downcasting
p.ParentsMethod(); //inside ParentsMethod
p.OverriddenMethod(); //inside Parent's OverriddenMethod
c.ParentsMethod(); //inside ParentsMethod
c.ChildsMethod(); //inside ChildsMethod
c.OverriddenMethod(); //inside Child's OverriddenMethod
pCast.ParentsMethod(); //inside ParentsMethod
pCast.OverriddenMethod(); //inside Child's OverriddenMethod **Runtime Polymorphism/Dynamic Binding
}
}
class Parent{
Parent(){
System.out.println("Inside Parent's Constructor");
}
void OverriddenMethod(){
System.out.println("inside Parent's OverriddenMethod");
}
void ParentsMethod(){
System.out.println("inside ParentsMethod");
}
}
class Child extends Parent{
Child(){
System.out.println("Inside Child's Constructor");
}
void OverriddenMethod(){
System.out.println("inside Child's OverriddenMethod");
}
void ChildsMethod(){
System.out.println("inside ChildsMethod");
}
}
P.S.:- Be careful for the "**".
public class InheritanceConcept {
public InheritanceConcept() {
System.out.println("Inside Polymorphism Constructor");
}
public static void main(String args[]) {
Parent p = new Parent();
Child c = new Child();
Parent pCast = new Child();
// Child cCast = (Child) new Parent(); //Class Cast Exception **Downcasting
p.ParentsMethod(); //inside ParentsMethod
p.OverriddenMethod(); //inside Parent's OverriddenMethod
c.ParentsMethod(); //inside ParentsMethod
c.ChildsMethod(); //inside ChildsMethod
c.OverriddenMethod(); //inside Child's OverriddenMethod
pCast.ParentsMethod(); //inside ParentsMethod
pCast.OverriddenMethod(); //inside Child's OverriddenMethod **Runtime Polymorphism/Dynamic Binding
}
}
class Parent{
Parent(){
System.out.println("Inside Parent's Constructor");
}
void OverriddenMethod(){
System.out.println("inside Parent's OverriddenMethod");
}
void ParentsMethod(){
System.out.println("inside ParentsMethod");
}
}
class Child extends Parent{
Child(){
System.out.println("Inside Child's Constructor");
}
void OverriddenMethod(){
System.out.println("inside Child's OverriddenMethod");
}
void ChildsMethod(){
System.out.println("inside ChildsMethod");
}
}