static variable vs non static variable

前端 未结 4 865
遥遥无期
遥遥无期 2020-12-20 08:37

I have defined an object and declared a static variable i. In the get() method, when I try to print the instance and class variable, both print the

相关标签:
4条回答
  • 2020-12-20 09:18

    static is a class level variable and non static is an instance variable(object level variable) . So here you declare only static variable and call them different way but same meaning.

    this.i
    test.i
    

    both treated as class level variable or static variable.

    0 讨论(0)
  • 2020-12-20 09:32

    The field i is declared as static. You can access static fields either with the YourClass.StaticField or instance.StaticField. So both of

    this.i
    test.i
    

    are referring to the same value in the context of an instance method of your test class.

    It's considered bad practice to access a static field with this.i or instance.i.

    0 讨论(0)
  • 2020-12-20 09:34

    No, there's only one variable - you haven't declared any instance variables.

    Unfortunately, Java lets you access static members as if you were accessing it via a reference of the relevant type. It's a design flaw IMO, and some IDEs (e.g. Eclipse) allow you to flag it as a warning or an error - but it's part of the language. Your code is effectively:

    System.out.println("Value of i = " + test.i);
    System.out.println("Value of static i = " + test.i);
    

    If you do go via an expression of the relevant type, it doesn't even check the value - for example:

    test ignored = null;
    System.out.println(ignored.i); // Still works! No exception
    

    Any side effects are still evaluated though. For example:

    // This will still call the constructor, even though the result is ignored.
    System.out.println(new test().i);
    
    0 讨论(0)
  • 2020-12-20 09:37

    you didn't declare any instance variable in here.only one static variable.if you declare instance variable without assigning value,then if you try to print that instance variable value using "this" key word you can get default value as 0.

    0 讨论(0)
提交回复
热议问题