集册 Java实例教程 用字段和方法创建一个类

用字段和方法创建一个类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

763
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
用字段和方法创建一个类

class BicycleDemo {
/**
 * 时 代 J a v a 公 众 号 - N o w J a v  a . c o m 提 供 
**/

    public static void main(String[] args) {


        // Create two different 

        // Bicycle objects

        Bicycle bike1 = new Bicycle();

        Bicycle bike2 = new Bicycle();


        // Invoke methods on 

        // those objects

        bike1.changeCadence(50);

        bike1.speedUp(10);

        bike1.changeGear(2);

        bike1.printStates();


        bike2.changeCadence(50);

        bike2.speedUp(10);

        bike2.changeGear(2);
        /**
        nowjava - 时  代  Java 提供 
        **/

        bike2.changeCadence(40);

        bike2.speedUp(10);

        bike2.changeGear(3);

        bike2.printStates();

    }

}

class Bicycle {


    int cadence = 0;

    int speed = 0;

    int gear = 1;


    void changeCadence(int newValue) {

        cadence = newValue;

    }


    void changeGear(int newValue) {

        gear = newValue;

    }


    void speedUp(int increment) {

        speed = speed + increment;

    }


    void applyBrakes(int decrement) {

        speed = speed - decrement;

    }


    void printStates() {

        System.out.println("cadence:" + cadence + " speed:" + speed

                + " gear:" + gear);

    }

}


展开阅读全文