类在Java中可以具有的变量类型是什么?


本文向大家介绍类在Java中可以具有的变量类型是什么?,包括了类在Java中可以具有的变量类型是什么?的使用技巧和注意事项,需要的朋友参考一下

类在Java中可以具有三种不同类型的变量:局部变量,实例变量类/静态变量。

 局部变量

Java中的局部变量可以在方法代码块 构造函数中局部声明。当程序控件输入方法,代码块构造函数时,将创建局部变量;当程序控件离开方法,代码块和构造函数时,将销毁局部变量。局部变量必须用一些值初始化

示例

public class LocalVariableTest {
   public void show() {
      int num = 100; // local variable      System.out.println("The number is : " + num);
   }
   public static void main(String args[]) {
      LocalVariableTest test = new LocalVariableTest();
      test.show();
   }
}

输出结果

The number is : 100


实例变量

Java中的实例变量可以在方法构造函数外部但在类内部声明。这些变量在创建对象时创建,在销毁对象时销毁

示例

public class InstanceVariableTest {
   int num; // instance variable
   InstanceVariableTest(int n) {
      num = n;
   }
   public void show() {
      System.out.println("The number is: " + num);
   }
   public static void main(String args[]) {
      InstanceVariableTest test = new InstanceVariableTest(75);
      test.show();
   }
}

输出结果

The number is : 75


静态/类变量

静态/类变量可以使用被限定静态关键字。这些变量 在类内部声明,但在方法代码块外部 声明。一类/静态变量可以创建该节目的开始 破坏该程序结束

示例

public class StaticVaribleTest {
   int num;   static int count; // static variable
   StaticVaribleTest(int n) {
      num = n;
      count ++;
   }
   public void show() {
      System.out.println("The number is: " + num);
   }
   public static void main(String args[]) {
      StaticVaribleTest test1 = new StaticVaribleTest(75);
      test1.show();
      StaticVaribleTest test2 = new StaticVaribleTest(90);
      test2.show();
      System.out.println("The total objects of a class created are: " + count);
   }
}

输出结果

The number is: 75
The number is: 90
The total objects of a class created are: 2