-4

I understand why "return a;" signals an error (because 'a' is non-static attribute and I'm trying to refer to it in a static method), but I don't understand why "return x.a;" doesn't signal an error. The 'a' attribute of 'x' is still non-static, shouldn't it be an error?

    class A{
        private int a=0;
        private static int b =0;
    
        public int m(){
            return a;
        }
    
        public static int n(A x){
            return x.a;//not an error
            return a;//error
        }
    }
6
  • 2
    The method n may be static but it's being given an instance x which does have the non-static attributes. return a is an error because that's not an int, nothing to do with static or not. Commented Mar 21, 2022 at 16:59
  • What does a represent? do you mean the int a field? Commented Mar 21, 2022 at 16:59
  • 1
    Why should it be any different? a is not static so you can't access it in a static context. x is provided as an argument so you can access its fields via the instance Commented Mar 21, 2022 at 16:59
  • "I don't understand why "return x.a;" doesn't signal an error." first let us know what makes you think that there should be an error here. What is wrong with this code in your opinion? What do you think static means? Commented Mar 21, 2022 at 17:06
  • x.a is the field of the instance x. It works because it's a non-static field used with an instance (x). In return a , a is a non-static field, but accessed from a static context (the method n). Commented Mar 21, 2022 at 17:14

1 Answer 1

1

but I don't understand why "return x.a;" doesn't signal an error

return x.a is valid because x is accessible as a local variable inside the static method and is an instance of A. a is an instance property on the instance of A so x.a is perfectly valid.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.