2

The result of this code is different depend on type of reference variable does this mean variables (int a) are bounded in static way

class A{
    int a = 10;
}
public class Main extends A {
    int a = 30;         
    public static void main(String[] args){             
        A m = new Main();
        System.out.println("A : " + m.a);
    }
}
1
  • Why are you shadowing the original value of a? Commented Feb 14, 2021 at 10:04

3 Answers 3

3

This is not just like static or dynamic binding. There is no polymorphism for fields in Java, only for methods.

Variables decisions are always taken at compile-time.

So, during the upcasting base class variable will be taken.

Sign up to request clarification or add additional context in comments.

2 Comments

This is what iam asking , does it means variables are always static biding or does biding is a term only for polymorphism
yeah. understand.
0

The variable m you have declared is of type A so the output would be 10. Instead if you have initialized m as Main m = new Main();, then the output would have been 30. This is because, the object is of type Main and since Main also has a field a, this would override the parent field a.

Comments

0

You have two object's type (A, Main) both from them have their own meaning for a variable a, so when your variable m has type A you get value 10 and if variable m has type Main you will get value 30.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.