变量类型
int a, b, c; // 声明三个int型整数:a、 b、c
int d = 3, e = 4, f = 5; // 声明三个整数并赋予初值
String s = "runoob"; // 声明并初始化字符串 s
double pi = 3.14159; // 声明了双精度浮点型变量 pi
char x = 'x'; // 声明变量 x 的值是字符 'x'。
静态变量或类变量(Class Variables)
属于类而不是实例,所有该类的实例共享同一个类变量的值
public class ExampleClass {
static int classVar; // 类变量
}
public class AppConfig {
public static final String APP_NAME = "MyApp";
public static final String APP_VERSION = "1.0.0";
public static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mydb";
public static void main(String[] args) {
System.out.println("Application name: " + AppConfig.APP_NAME);
System.out.println("Application version: " + AppConfig.APP_VERSION);
System.out.println("Database URL: " + AppConfig.DATABASE_URL);
}
}
public class Counter {
private static int count = 0;
public Counter() {
count++;
}
public static int getCount() {
return count;
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println("目前为止创建的对象数: " + Counter.getCount());
}
}
参数变量
引用传递
Java 中的对象类型采用引用传递方式传递参数变量的值。
局部变量&成员变量(实例变量)
局部变量没有默认值,成员变量具有默认值。
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 );
System.out.println("薪水 : " + salary);
}
public static void main(String[] args){
Employee empOne = new Employee("RUNOOB");
empOne.setSalary(1000.0);
empOne.printEmp();
}
}
静态变量和实例变量区别
public class StaticTest {
private static int staticInt = 2;
private int random = 2;
public StaticTest() {
staticInt++;
random++;
System.out.println("staticInt = "+staticInt+" random = "+random);
}
public static void main(String[] args) {
StaticTest test = new StaticTest();
StaticTest test2 = new StaticTest();
}
}
输出结果:
staticInt = 3 random = 3
staticInt = 4 random = 3