Can you access non static variable in static context?
Can you access non static variable in static context?
No, you cannot directly access a non-static variable from a static context in Java. A static context, such as a static method, belongs to the class itself rather than an instance of the class. Since non-static variables are instance variables, they belong to specific instances of the class and require an object reference to be accessed.
To access a non-static variable from a static context, you must first create an instance of the class that the variable belongs to. Once you have an instance, you can use that instance to reference the non-static variable. Here's an example to illustrate this:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.