1先创建一个类
package lianxi; public class lei { //属性 //成员变量 //品牌 String PinPai; //速度 double SuDu; //油耗 double YouLiang =0; //行为 //方法 void-没有返回值,如果有返回值,要写明返回值的数据类型 //加油 void jiaYou(double yl){ YouLiang+=yl; System.out.println("这次加了"+yl+"升油,车的当前油量为 "+YouLiang); } double CaoLiang=50; double NaiLiang; String MingZi="牛XX"; void chi(double y2){ CaoLiang-=y2; NaiLiang+=y2; //System.out.println("这次吃了"+y2+"吨草,产了"+y2+"吨奶"); } String ShuaiGe="张昊哲"; String YouduoShuai="帅的惊天动地"; double GeijiFen; void hao(double y2){ GeijiFen+=y2; } String CheMing; double JiaGe; double YouHao; double JiaSu; double GongLi; void jg(double x1){ JiaGe=x1; } void yh(double x2){ YouHao=x2; } void js(double x3){ JiaSu=x3; //父类 Object o;//最大的父类 } }
2在另一个类里面可以直接用
package lianxi; public class shiyonglei { public static void main(String[] args) { //实例化lei lei BMW=new lei(); BMW.PinPai="宝马"; System.out.println("车的品牌="+BMW.PinPai); BMW.jiaYou(40); System.out.println("车的品牌="+BMW.PinPai+",当前油量="+BMW.YouLiang); lei CN=new lei(); CN.chi(30); System.out.println(CN.MingZi+" 吃了30吨草,还剩"+ CN.CaoLiang+"吨"+"产了"+CN.NaiLiang+"吨奶"); lei CC=new lei(); CC.hao(100); System.out.println("谁最帅?答:"+CC.ShuaiGe); System.out.println("有多帅?答:"+CC.YouduoShuai); System.out.println("给几分?答:"+CC.GeijiFen); lei car=new lei(); car.CheMing="宝驴"; System.out.println("车名:"+car.CheMing); car.jg(100); System.out.println("车的价格="+car.JiaGe); car.yh(8.5); System.out.println("车的油耗="+car.YouHao); car.js(12.75); System.out.println("车的加速="+car.JiaSu); car.CheMing="宝猪"; System.out.println("车名:"+car.CheMing); car.jg(98.434); System.out.println("车的价格="+car.JiaGe); car.yh(4.32); System.out.println("车的油耗="+car.YouHao); car.js(11.435); System.out.println("车的加速="+car.JiaSu); } }