java变量的几种类型

局部变量:

age是一个局部变量。定义在pubAge()方法中,它的作用域就限制在这个方法中。

	public class Test{
		
		public void pupAge(){
		
		int age = 0;  /*age必须初始化不然报错*/
		
		age = age + 7;
		
		System.out.println("Puppy age is :" + age);
		
		}
		
		
		public static void main(String args[]){
		
		Test test = new Test();
		
		test.pupAge();
		
		}
		
		}
//运行结果:Puppy age is 7

成员变量: 

	import java.io.*;
	
	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("Ransika");
		
		empOne.setSalary(1000);
		
		empOne.printEmp();
	}
	
	}

运行结果:name : Ransika
 salary :1000.0

类变量(静态变量):

	import java.io.*;
	
	public class Employee1{
	//salary是静态的私有变量
		private static double salary;
	// DEPARTMENT是一个常量
		public static final String DEPARTEMENT = "Development";
	
		public static void main(String args[]){
	
			salary = 1000;
		
			System.out.println(DEPARTEMENT+"average salary:"+salary);
	
	}
	
	}

  运行结果:

Development average salary:1000

遇到的问题,java编译错误:解析时已到达文件结尾?

解决:缺少大括号,仔细查找!

posted @ 2015-11-08 22:12  千君君  阅读(563)  评论(0编辑  收藏  举报