public class SuperClass {
int var = 100;
public int getSqrt() {
return (int)Math.sqrt(var);
}
}
public class SubClass extends SuperClass {
int var = 225;
@Override
public int getSqrt() {
return (int)Math.sqrt(var);
}
}
public class TestVarOverriding
{
public static void main(String[] args) {
SuperClass superOb = new SubClass();
System.out.println(superOb.var);
//can not override the variable(structure).
System.out.println(superOb.getSqrt());
//Method overriding(behavior overriding)
}
}
Output:
100
15
Oops !
No overriding for variable.
Because we can only override
behavior and not structure.
Structure is set in stone once an object has
been created and memory has been allocated for it. Of course this is usually
true in statically typed languages.
Therefore the program will print the variable value of the parent class and returned sqrt value of the child class (Overriding class).
Therefore the program will print the variable value of the parent class and returned sqrt value of the child class (Overriding class).
No comments:
Post a Comment