关于现实世界的对象真的很多很多,以下是最近探讨的一些对象:
这样定义是否存在争议呢?
中秋节与教师节碰杯,正值花好与月圆,桃李满天下!
还有月越来越圆,愿事事如愿!
手机:价钱(price),品牌(name),型号(number), 方法(void):可以通过售卖改变价格、用户给予新命名、重新上架新的型号。
/**
* 创建一个手机类
*/
class Phone{
//设置它的状态
int Price = 3999;
String name = "";
int Model = 001;
//当它上架的时候会有不同的价格且附上新的值
void changePrice(int newValue){
Price = newValue;
}
//每一位购买它的会给它取新的名字
void changeName(String newName){
name = newName;
}
//每售卖一台手机就会有下一台型号的手机
void changeModel(int newNumber){
Model = newNumber;
}
//方法调用实现打印结果
void outcome(){
System.out.println(
"最终售价;"+Price
+"/n新手机的名字:"+name
+"/n下一部型号是:"+Model
);
}
}
方法的实现:
Phone phone1 = new Phone();
Phone phone2 = new Phone();
phone1.changePrice(3333);//卖出第一台手机
phone1.changeName("苹果14pro");
phone1.changeModel(717);
phone1.outcome();
phone2.changePrice(7999);
phone2.changeName("IQOO Z14pro");
phone2.changeModel(1717);
phone2.outcome();
System.out.println(phone1);
System.out.println(phone2);
风扇:开、关;行为:开、关、换档、定时。
/**
* 创建一台风扇类
*/
class Fan {
int Open = 1;//开
int Close = 0;//关
int GearSpeed = 0;//档速
int Timing = 0;//定时
//是否打开
void changeOpen(int newValue){
Open = newValue;//0或1
}
//是否关闭
void changeClose(int newValue){
Close = newValue;//0或1
}
//是否换档
void ShiftGears(int increment){
GearSpeed = GearSpeed + increment;//提高档速 0/1/2/3档
}
void changeTiming(int newTime){
Timing = Timing + newTime;//设置定时
}
void outcome(){
System.out.println(
"当前打开状态为;"+Open
+"/n关闭状态为:"+Close
+"/n当前档速为:"+GearSpeed
+"/n设置定时:"+Timing+"min!"
);
}
}
行为:开、关、换档、定时。方法的实现:
Fan fan1 = new Fan();//传入一台风扇
fan1.changeOpen(1);//打开状态
fan1.changeClose(0);//当打开状态为1时,关闭状态就应该是0
fan1.ShiftGears(2);//当前为2档风速
fan1.changeTiming(30);//定义当时时间30分钟
fan1.outcome();
System.out.println(fan1);
以上实现了类和对象之间的关系。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/288684.html