Câu hỏi phỏng vấn Java
Câu hỏi

Can you access non static variable in static context?

Câu trả lời

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:

java Copy
public class MyClass {
    private int nonStaticVariable; // Non-static variable

    public static void main(String[] args) {
        MyClass instance = new MyClass(); // Create an instance of MyClass
        instance.nonStaticVariable = 10; // Access non-static variable through the instance
        System.out.println(instance.nonStaticVariable); // Output the value of the non-static variable
    }
}

In the example above, nonStaticVariable is a non-static variable. The main method is static, so it cannot directly access nonStaticVariable. Instead, it creates an instance of MyClass and accesses nonStaticVariable through that instance[1][2][3][4][5].

Citations:
[1] https://www.javatpoint.com/why-non-static-variable-cannot-be-referenced-from-a-static-context-in-java
[2] https://javarevisited.blogspot.com/2012/02/why-non-static-variable-cannot-be.html?m=1
[3] https://www.j...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is the importance of hashCode() and equals() methods?

junior

What is an Java Applet?

junior

What are Directives?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào