In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
在现实世界中,你经常会发现许多单独的物体都是同类的。可能还有成千上万的其他自行车,都是相同的品牌和型号。每辆自行车都是用同一套蓝图建造的,因此包含相同的部件。在面向对象的术语中,我们说你的自行车是被称为自行车的对象类的一个实例。类是用来创建单个对象的蓝图。
理解面向对象的思想
对象有状态和行为
例如狗 状态(名字,颜色,品种...) 行为(走路,摇尾巴,抓东西...)
讨论一个对象时,问自己两个问题:1.这个对象可能处于什么状态? 2.这个对象可以执行什么可能的行为?
类:用来创建单个对象
package bicly;
public class BicycleDemo {
public static void main(String[] args) {
Bicycle b1; // 声明对象b1
b1 = new Bicycle(); // 创建Bicycle类给b1
Bicycle b2 = new Bicycle(); // 声明+创建对象b2
int a; // 声明一个变量a
a = 100; // 赋值100给变量a
b1.setCadence(10); // 调用类的方法修改它的状态
b1.setSpeed(20);
b1.setGear(5);
b1.printStates();
b2.setCadence(30);
b2.setSpeed(40);
b2.setGear(6);
b2.printStates();
}
}
class Bicycle {
// 状态
int cadence = 0;
int speed = 0;
int gear = 1;
// 行为
public int getCadence() {
return cadence;
}
public void setCadence(int cadence) {
this.cadence = cadence;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getGear() {
return gear;
}
public void setGear(int gear) {
this.gear = gear;
}
void printStates(){
System.out.println(" cadence: " +
cadence + " speed: " +
speed + " gear: " +
gear);
}
}
输出结果:
标签:java,gear,int,b1,speed,public,cadence From: https://www.cnblogs.com/liudelantu/p/17625132.htmlcadence: 10 speed: 20 gear: 5
cadence: 30 speed: 40 gear: 6