例子来源:http://docs.oracle.com/javase/tutorial/java/concepts/class.html
Bicycle.java文件
1 class Bicycle{ 2 int cadence = 0; 3 int speed = 0; 4 int gear = 1; 5 6 void changeCadence(int newValue){ 7 cadence = newValue; 8 } 9 10 void changeGear(int newValue){ 11 gear = newValue; 12 } 13 14 void speedUp(int increment){ 15 speed = speed + increment; 16 } 17 18 void applyBrakes(int decrement){ 19 speed = speed - decrement; 20 } 21 22 void printStates(){ 23 System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear); 24 } 25 }
BicycleDemo.java
1 class BicycleDemo{ 2 public static void main(String[] args){ 3 Bicycle bike1 = new Bicycle(); 4 Bicycle bike2 = new Bicycle(); 5 6 bike1.changeCadence(50); 7 bike1.speedUp(10); 8 bike1.changeGear(2); 9 bike1.printStates(); 10 11 12 bike2.changeCadence(50); 13 bike2.speedUp(10); 14 bike2.changeGear(2); 15 bike2.changeCadence(40); 16 bike2.speedUp(10); 17 bike2.changeGear(3); 18 bike2.printStates(); 19 } 20 }
控制台操作方法:
javac Bicycle.java //编译Bicycle.java文件为字节码,生成Bicycle.class文件
javac BicycleDemo.java //编译BicycleDemo.java文件为字节码,生成BicycleDemo.class文件
java BicycleDemo //运行BicycleDemo
F:\Code\java>java BicycleDemo
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3