📜  实例变量和类变量的区别

📅  最后修改于: 2021-09-15 01:03:15             🧑  作者: Mango

实例变量它基本上是一个没有静态修饰符的类变量,通常由所有类实例共享。在不同的对象中,这些变量可以有不同的值。它们与类的特定对象实例相关联,因此,实例变量的内容完全独立于一个对象实例与其他对象实例。

例子:

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

类变量:它基本上是一个静态变量,可以在类级别的任何地方使用静态声明。在不同的对象中,这些变量只能有一个值。这些变量不绑定到类的任何特定对象,因此可以在类的所有对象之间共享。

例子:

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

Instance 和 Class 变量之间的表格差异

Instance Variable

Class Variable

It is a variable whose value is instance-specific and now shared among instances.   It is a variable that defines a specific attribute or property for a class.  
These variables cannot be shared between classes. Instead, they only belong to one specific class.   These variables can be shared between class and its subclasses. 
It usually reserves memory for data that the class needs.   It usually maintains a single shared value for all instances of class even if no instance object of the class exists.  
It is generally created when an instance of the class is created.   It is generally created when the program begins to execute.  
It normally retains values as long as the object exists.   It normally retains values until the program terminates.
It has many copies so every object has its own personal copy of the instance variable.  It has only one copy of the class variable so it is shared among different objects of the class.  
It can be accessed directly by calling variable names inside the class.   It can be accessed by calling with the class name.  
These variables are declared without using the static keyword.   These variables are declared using the keyword static.  
Changes that are made to these variables through one object will not reflect in another object.   Changes that are made to these variables through one object will reflect in another object. 

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。