What’s the difference between a class variable and an instance variable?

 

What’s the difference between a class variable and an instance variable?

 

Knowing the terminology is important. Instance variables and class variables are both member variables. They are both member variables because they are both associated with aspecificclass. But, there are differences between instance variables and class variables.

Instance variables

Instance variables belong to an instance of a class. Another way of saying that is instance variables belong to an object, since an object is an instance of a class. Every object has it’s own copy of the instance variables. Here is what a declaration of an instance variable would look like:

Example of an instance variable:

class Taxes
{
  int count;
  /*...*/
}

Class variables – also known as static member variables

Class variables, however, only haveonecopy of the variable(s) shared with all instances of the class. It’s important to remember thatclass variables are also known as static member variablesin C++, Java, and C#. Each object of the class does not have its own copy of a class variable. Instead, every object shares theone and onlycopy of that class variable – and any changes made to that copy are seen by all of the objects of that class. Here is what a class variable – or a static member variable – would look like in C++:

Example of a class variable:

class Taxes
{
  static int count;
  /*...*/
}

Difference between class and instance variables

Now, it should be clear what the difference between instance and class variables is. Class variables only have one copy that is shared by all the different objects of a class, whereas every object has it’s own personal copy of an instance variable. So, instance variables across different objects can have different values whereas class variables across different objects can have only one value.

Class and Instance variables are both Member variables

Here’s a little diagram to help you remember the differences between instance and class variables:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值