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
原文:http://www.cnblogs.com/kaituorensheng/p/5750739.html