In this tutorial, I will be sharing what are Instance variables in java, example of an Instance Variable, properties of instance variables in java, and default values for instance variables. Let's dive deep into the topic.
Read Also: Types of Variables in Java
What are Instance Variables in Java?Instance variables are defined inside a class but outside any method declaration. These variables are defined without the static keyword and are only initialized when the class is instantiated i.e. object of that class is created. These variables belong to each unique object and have scope only within that object i.e not shared among instances.
Example of Instance Variable in JavaThe following code defines instance variables for the empName, empId for employee objects.
Each instance of the Employee class can have its own unique values for those two fields.
Rules Associated With Instance Variable in Java
- Instance variable can use any access modifiers (private, public, protected, or default).
- Instance variable can be marked final
- Instance variable can be marked transient
- Instance variable cannot be marked static otherwise it will become a class variable.
- Instance variable cannot be marked abstract
- Instance variable cannot be marked synchronized
- Instance variable cannot be marked strictfp
- Instance variable cannot be marked native
Important Points About Instance Variable in Java
- Instance variables belong to each unique object of the class.
- Instance variables are created only when a new object is created using a 'new' keyword in Java.
- Instance variables associated with an object are destroyed once the object is destroyed.
- Instance variables will have a default value if not initialized.
Default Value of Instance Variable in Java
Java Program for Instance Variable
Value of Instance Variable is 5
Value of Instance Variable is 10
That's all for today. Please mention in comments in case you have any questions regarding the instance variable in java with example.