Object Variables vs Class Variables in Java

后端 未结 5 1304
刺人心
刺人心 2020-12-16 17:39

I am in the process of learning Java and I don\'t understand the difference between Object Variables and Class Variable. All I know is that in order for it to be a Class Var

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 17:59

    Let's say you have a blueprint of a car called ToyotaYaris, in which you might have a variable called maxSpeed. All the cars made with that blueprint (its instances) will have the same maximum speed, so that variable should belong to the blueprint, and not the individual cars. If the maxSpeed changes in the blueprint, so will it change in all the cars it produces.

    However, on each car, you might want to have another variable called speed. This variable can't belong to the blueprint because each car can be driving at different speeds independently of each other, so you need that variable to belong to each specific instance of ToyotaYaris.

    Therefore:

    class ToyotaYaris {
        static int maxSpeed;
        int speed;
    }
    

提交回复
热议问题