Inheritance issue : Results are different on creating same class object

This question already has an answer here:

  • Does polymorphism apply on class attributes in Java?

    8 answers

Case 1:
In the below example if i call a.i it is printing 10 as answer. But A a = new B(); isn”t this like object of b is getting created so value 20 should be printed instead of 10.

class A
{
    int i = 10;
}

class B extends A
{
    int i = 20;
}

public class MainClass
{
    public static void main(String[] args)
    {
        A a = new B();
        System.out.println(a.i);
    }
}

Case 2:
Also if i create the same program as above using methods inside classes instead of printing variable values as in above case then result is different :

class A{

    void test(){
        System.out.println("hi");
    }
}

    class B extends A{
        void test(){
            System.out.println("hello");
        }
}


public class Test {
    public static void main(String[] args) {

                A a=new B();
                System.out.println(a.test);
    }

Now in this case hi is printed instead of hello , so why is the behavior different when i try to print variable value and when using methods? Overiding happens between the methods only and not with variables?

In Java only methods can be overriden, not instance variables.

When you declare a field with the same name as an existing field in a superclass, the new field hides the existing field. The existing field from the superclass is still present in the subclass, and can even be used

Check these –

Java Tutorial – Hiding Fields

JLS Example – Hiding of instance fields

Because what you have in the first example has nothing to do with polymorphism as fields read are not dynamically dispatched.

What you have however is a name shadowing, so i in the statement A.i refers to the field declared in A and B.i is invisible at this point.