Java语言支持的变量类型有:
1 public class Variable{ 2 static int allClicks=0;//类变量 3 String str="hello world";//实例变量 4 public void method(){ 5 int I=0;//局部变量 6 } 7 }
1 public class Test{ 2 public void pupAge(){ 3 int age=0;//局部变量必须初始化,否则在编译时会出错 4 age=age+7; 5 System.out.println("小狗的年龄是:"+age); 6 } 7 public static void main(String[] args){ 8 Test test=new Test();//默认构造方法 9 test.pupAge(); 10 } 11 }
1 public class Test { 2 3 int age;//实例变量 4 5 public void pupAge(int age) { 6 this.age = age; 7 System.out.println("pup‘s age is " + age); 8 } 9 10 public static void main(String[] args) { 11 Test test = new Test();//创建对象test 12 test.pupAge(5); 13 } 14 }
public class Employee { public String name;//这个实例变量对子类(subclass)可见 private double salary;//滴油变量,仅在该类(superclass)可见 //构造器中对name赋值 public Employee(String empName) { this.name = empName; } //设定salary的值 public void setSalary(double empSal) { this.salary = empSal; } //打印信息 public void printEmp() { System.out.println("名字:" + name); System.out.println("薪水:" + salary); } public static void main(String[] args) { Employee empOne = new Employee("RUNOOB"); empOne.setSalary(1000); empOne.printEmp(); } }
1 public class Employee01 { 2 3 private static double salary;//salary是静态的私有变量。 4 public static final String DEPARTMENT = "开发人员"; 5 6 public static void main(String[] args) { 7 salary = 1000; 8 System.out.println(DEPARTMENT + "平均工资" + salary); 9 } 10 }
注意:如果其他类想要访问该变量,可以这样访问:Employee.DEPARTMENT。
原文:https://www.cnblogs.com/2020yl/p/12238887.html