放弃了N本书后,终于找到了又新又靠谱的教程~
来自官网的代码,适用最新的Java8,每个代码例子都有输出验证,十分适合练手。唯一的缺点是没有中文,我一般就看这里的代码,然后去上MOOC补补理论基础~
https://docs.oracle.com/javase/tutorial/tutorialLearningPaths.html
class
需要一个main
函数调用其他的class
,以下创建了一个Bicycle
的类,通过BicycleDemo
去调用Bicycle
的函数和输出。起名靠谱点,IDEA写的时候直接就可以读懂而不用加额外注释了。
//Bicycle.java file
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void ChangeCadence(int newCadence) {
cadence = newCadence;
}
void changeGear(int newGear){
gear = newGear;
}
void speedUp(int increSpeed){
speed = speed + increSpeed ;
}
void applyBrakes(int decreSpeed){
speed = speed - decreSpeed;
}
void printStates(){
System.out.printf("cadence: %s ; speed : %s ; gear : %s \n",cadence,speed,gear);
}
}
// BicycleDemo.java file
class BicycleDemo {
public static void main(String[] args) {
//create two bicycles
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
bike1.ChangeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.ChangeCadence(50);
bike2.speedUp(50);
bike2.changeGear(2);
bike2.ChangeCadence(40);
bike2.applyBrakes(5);
bike2.printStates();
}
}
//output
cadence: 50 ; speed : 10 ; gear : 2
cadence: 40 ; speed : 45 ; gear : 2
Inheritance
主要提到了extends 主类,待做更深入的例子。
class MountainBike extends Bicycle {
// new fields and methods defining
// a mountain bike would go here
}
改名字的想法来自《代码整洁之道》,代码质量与其整洁度成正比。
只要找到适合的教程,学习速度就能飞起来~
2018.6.20