Wednesday, 16 September 2015

Overriding a super class' instance variables

public class SuperClass {
       int var = 100;

       public int getSqrt() {
              return (int)Math.sqrt(var);

public class SubClass extends SuperClass {
       int var = 225;
       public int getSqrt() {
              return (int)Math.sqrt(var);

public class TestVarOverriding {

       public static void main(String[] args) {
              SuperClass superOb = new SubClass();
                        //can not override the variable(structure).
                        //Method overriding(behavior overriding)

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).

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...