Java Inheritance- Method and Variable overriding

A very simple example to understand overriding concept in java

Parent Class-

public class parent {

int pval=10;
parent()
{
System.out.println(“creating parent”);
}

public void area()
{
System.out.print(“area of parent:”);
System.out.println(pval);
}
}

Child class-

public class child extends parent{
int cval=5;
int pval=15;
child()
{
System.out.println(“creating child”);
}

child(String str)
{
System.out.println(“hello:”+str);
}

public void area()
{
System.out.print(“area of child:”);
System.out.println(cval);
}

public static void main(String s[])
{
child c=new child();
c.area();
System.out.println(“c.pval:”+c.pval);
System.out.println(“—————————-“);
child c1=new child(“kamal”);
System.out.println(“—————————-“);
parent p=new parent();
p.area();
System.out.println(“p.pval:”+p.pval);
System.out.println(“—————————-“);
parent pc=new child();
pc.area();
System.out.println(“pc.pval:”+pc.pval);
System.out.println(“—————————–“);
}

}

output

creating parent
creating child
area of child:5
c.pval:15
—————————-
creating parent
hello:kamal
—————————-
creating parent
area of parent:10
p.pval:10
—————————-
creating parent
creating child
area of child:5
pc.pval:10
—————————–

Look closely at the last set of output, that is interesting. You can see when we refer to child object with parent class reference, the method being called is from child class as method was overridden, but the pval member variable was not overridden.

Now as member variables are not overridden, compiler uses static binding as it already know which variable is being referred to, whereas in case of parent class object calling a method which is overridden, compiler will not know beforehand which method should be called, so it will leave that decision to runtime, hence dynamic binding.