I don't understand why the static method can't receive a non-static member, but it's an example.

Asked 2 years ago, Updated 2 years ago, 22 views

class Number {

int n;
public Number(int n) { this.n = n; }

}

public class Example {

static void plusTen(Number x) { x.n += 10; }
public static void main(String args[]) {
    Number ob = new Number(5);
    plusTen(ob);
    System.out.println(ob.n);
}

}

It's a practice question for "Luxury Java Essential" The static method cannot be accessed as a non-static member If then, In the static void plus Ten (Number x) line, Since x.n is a non-static member, shouldn't there be a compilation error? But when I actually coded it, Here's the result. Please help me. I don't understand.

java

2022-09-20 16:57

1 Answers

You don't have to tell whether x.n is ob or static, but it's accessible because it's passed on to the function's factor. Number x is the local variable of the plusTen function.


2022-09-20 16:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.