Object Variables vs Class Variables in Java

后端 未结 5 1303
刺人心
刺人心 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 18:02

    The difference between a static variable or a class variable and an instance variable or a object variable is pretty simple. Every object you create has its own copy of its very own instance variables. Where as if there is a static variable in the class then only one copy of that static variable exists for all the objects. For example

    public class JellyBean{
    
        // instance variables every jellyBean object will have its own 
        // variable for color
        String color;
    
        // static variable only one copy of this variable exists for 
        // all jellyBean objects.
        static int totalNumberOfJellyBeans;
    
    }//end class 
    

    If you created 2 jellybean objects you would have two variables for Color because each jellybean has its own variable for color. And 1 variable for totalNumberOfJellyBeans because both jellyBean objects use this one class variable.

提交回复
热议问题