Java 引用变量

原文: https://javabeginnerstutorial.com/core-java-tutorial/java-reference-variable/

引用变量用于引用对象。 它们以无法更改的特定类型声明。

引用变量的类型

  • 静态变量
  • 实例变量
  • 方法参数
  • 局部变量

静态变量示例

  1. class test {
  2. //below variable is static variable means it is class level variable
  3. static int i;
  4. public static void main(String[] args) {
  5. // As i is an static variable it can be accessed directly without using any object
  6. System.out.println("Value before calling method1: " + i);
  7. test t1 = new test();
  8. t1.method1();
  9. System.out.println("Value after calling method1: " + i);
  10. t1.method2();
  11. System.out.println("Value after calling method2: " + i);
  12. }
  13. void method1() {
  14. i++;
  15. }
  16. void method2() {
  17. i++;
  18. }
  19. }

实例/局部/方法参数示例

  1. class MPE {
  2. // Instance Variable
  3. int i;
  4. public static void main(String[] args) {
  5. /*
  6. * Here i is an Instance variable.
  7. */
  8. test t1 = new test();
  9. System.out.println("Value before calling method1: " + t1.i);
  10. }
  11. /*
  12. * Here j is a method parameter. And k is a local variable.
  13. *
  14. * Note**: Local variables life is only till the end of method
  15. */
  16. void method1(int j) {
  17. int k;
  18. i = j;
  19. /*
  20. * Local Variable(k)'s life ends once execution for this method
  21. * completes. As k is local is variable it needs to be initialized
  22. * before we can use it. But as it is not getting used here, it can stay here without initializing
  23. */
  24. }
  25. }