
代码如下:
public class Demo {
?? ?public static void main(String[] args) { ?? ??? ?// TODO Auto-generated method stub ?? ??? ?Engine benzEngine=new Engine(); ?? ??? ?Car myCar=new Car("Benz",130,"red","suv",18,benzEngine); ?? ??? ?myCar.showInfo(); ?? ??? ? ?? ??? ?Car myCar2=new Car(); ?? ??? ?myCar2.showInfo(); ?? ?}
}
//汽车类
public class Car { ?? ?String carBrand; ?? ?int price; ?? ?String color; ?? ?String motorcycleType; ?? ?double oilConsumption; ?? ?Engine carEngine; ?? ? ?? ?/*构造代码块 ?? ?{ ?? ??? ?System.out.println("我是构造代码块"); ?? ?}*/ ?? ? ?? ?//构造方法 ?? ?public Car(){ ?? ??? ?carEngine=new Engine(4.5,220); ?? ?} ?? ?public Car(String _carBrand,int _price,String _color,String _motorcycleType,double _oilConsumption,Engine _engine){ ?? ??? ?carBrand=_carBrand; ?? ??? ?price=_price; ?? ??? ?color=_color; ?? ??? ?motorcycleType=_motorcycleType; ?? ??? ?oilConsumption=_oilConsumption; ?? ??? ?carEngine=_engine; ?? ?} ?? ? ?? ?public void start(){ ?? ??? ?System.out.println("小汽车启动,实际上发动机点火"); ?? ??? ?carEngine.start(); ?? ?} ?? ?public void stop(){ ?? ??? ?System.out.println("小汽车停止,实际上发动机熄火"); ?? ??? ?carEngine.stop(); ?? ?} ?? ? ?? ?public void showInfo(){ ?? ??? ?System.out.println("汽车信息-----------"); ?? ??? ?System.out.println("carBrand:"+carBrand); ?? ??? ?System.out.println("price:"+price); ?? ??? ?System.out.println("color:"+color); ?? ??? ?System.out.println("motorcycleType:"+motorcycleType); ?? ??? ?System.out.println("oilConsumption:"+oilConsumption); ?? ??? ?carEngine.showInfo(); ?? ?}
}
//引擎类
public class Engine { ?? ?double displacement; ?? ?int powerSize; ?? ? ?? ?public Engine(){ ?? ?} ?? ?public Engine(double _displacement,int _powerSize){ ?? ??? ?displacement=_displacement; ?? ??? ?powerSize=_powerSize; ?? ?} ?? ? ?? ?public void start(){ ?? ??? ?System.out.println("发动机点火"); ?? ?} ?? ?public void stop(){ ?? ??? ?System.out.println("发动机熄火"); ?? ?} ?? ? ?? ?public void showInfo(){ ?? ??? ?System.out.println("displacement:"+displacement); ?? ??? ?System.out.println("powerSize:"+powerSize); ?? ?} }
(编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|