变量是赋予内存位置的名称。它是程序中存储的基本单位。
- 存储在变量中的值可以在程序执行期间更改。
- 变量只是一个内存位置的名称。所有操作都是在内存位置的可变效果上完成的。
- 在Java,所有变量必须在使用前声明。
实例变量:这些变量在类内声明,但在方法、构造函数或块之外,并且始终获得默认值。
- 这些变量通常在我们创建对象时创建,并在对象销毁时销毁。
- 我们可以使用访问说明符,例如变量,如果没有指定访问说明符,则使用默认访问说明符。
- 每个对象都有自己的实例变量副本。
例子:
class Taxes
{
int count; // Count is an Instance variable
/*...*/
}
局部变量:这些变量在方法中声明,但没有任何默认值。
- 它们通常在我们进入方法或构造函数时创建,并在退出块或从方法调用返回时销毁。
- 它的范围通常限于一个方法,它的范围从它们声明的那一行开始。它们的作用域通常保持在那里,直到方法的右花括号出现。
- 局部变量的初始化是强制性的。
例子:
int area()
{
int length = 10; // Local variable
int breadth = 5; // Local variable
int rectarea = length*breadth; // Local variable
return rectarea;
}
实例变量与局部变量之间的表格差异:
Instance Variable |
Local Variable |
---|---|
They are defined in class but outside the body of methods. | They are defined as a type of variable declared within programming blocks or subroutines. |
These variables are created when an object is instantiated and are accessible to all constructors, methods, or blocks in class. | These variables are created when a block, method or constructor is started and the variable will be destroyed once it exits the block, method, or constructor. |
These variables are destroyed when the object is destroyed. | These variables are destroyed when the constructor or method is exited. |
It can be accessed throughout the class. | Its access is limited to the method in which it is declared. |
They are used to reserving memory for data that the class needs and that too for the lifetime of the object. | They are used to decreasing dependencies between components I.e., the complexity of code is decreased. |
These variables are given a default value if it is not assigned by code. | These variables do not always have some value, so there must be a value assigned by code. |
It is not compulsory to initialize instance variables before use. | It is important to initialize local variables before use. |
It includes access modifiers such as private, public, protected, etc. | It does not include any access modifiers such as private, public, protected, etc. |