面向对象封装内存布局,成员变量,成员方法,参数和返回值

面向对象封装内存布局,成员变量,成员方法,参数和返回值

面向对象内存布局

public class Car {//面向对象编程,不是面向过程编程
     //成员变量
    //汽车品牌
    String type;
    //汽车颜色
    String color;
    //汽车长度
    long length;
    //成员方法
    public void run(int gasoline){//gasoline是形式参数,形参可以有多个。用英文逗号隔开
        if (gasoline == 92){
            System.out.println("您加了92号汽油,汽车跑的很猛!");
        }else if (gasoline == 95){
            System.out.println("您加了95号汽油,您的汽车快飞起来了!");
        }else {
            System.out.println("您加的是水吧,您的汽车趴窝了!");
        }

    }
    public boolean start(){
        //随机生成一个0-1的double数字
        double random = Math.random();
        if (random > 0.8){
            System.out.println("车子正常启动!");
            return true;
        }else {
            System.out.println("车子坏了!");
            return false;
        }
    }

    public static void main(String[] args) {
        Car baoma = new Car();
        baoma.color = "red";
        baoma.length = 4518;
        baoma.type  = "baoma";

        Car benchi = new Car();
        benchi.color = "white";
        benchi.length = 4000;
        benchi.type  = "benchi";

        Car[] cars = {benchi,baoma};

        for (int i = 0; i < cars.length; i++) {
            System.out.println(cars[i].color+" "+cars[i].type+" "+cars[i].length);
        }


        benchi.run(95);
        boolean f = baoma.start();

        if (f){
            System.out.println("去秋名山飙车!");
        }else {
            System.out.println("去修理厂修车!");
        }
    }
}

white benchi 4000
red baoma 4518
您加了95号汽油,您的汽车快飞起来了!
车子正常启动!
去秋名山飙车!

Process finished with exit code 0

posted @ 2022-05-11 21:10  追风的羊  阅读(52)  评论(0)    收藏  举报