閱讀目錄
Java有3類變量
例子
package import_test; public class Dog { public void pupAge(){ int age = 1; int color; System.out.println("小狗的年齡是:" + age); } public static void main(String args[]){ Dog test = new Dog(); test.pupAge(); } }
例子中的age和color都是局部變量,但color沒賦值,系統不會默認賦值,例:
package import_test; public class Dog { public void pupAge(){ int age; age = age + 1; System.out.println("小狗的年齡是:" + age); } public static void main(String args[]){ Dog test = new Dog(); test.pupAge(); } }
編譯錯誤提示:Error:(6, 15) java: 可能尚未初始化變量age
例子
package import_test; public class Employee{ // 這個成員變量對子類可見 public String name; // 私有變量,僅在該類可見 private double salary; //在構造器中對name賦值 public Employee (String empName){ name = empName; } //設定salary的值 public void setSalary(double empSal){ salary = empSal; } public void printEmp(){ System.out.println("name : " + name ); System.out.println("salary :" + salary); } public static void main(String args[]){ Employee empOne = new Employee("Jim"); empOne.setSalary(2000); empOne.printEmp(); } }
結果
name : Jim salary :2000.0
import java.io.*; public class Employee { //salary是靜態的私有變量 private static double salary; // DEPARTMENT是一個常量 public static final String DEPARTMENT = "開發人員"; public static void main(String args[]){ salary = 10000; System.out.println(DEPARTMENT+"平均工資:"+salary); } }
執行結果
開發人員平均工資:10000.0 開發人員平均工資:10000.0