Java | Instance and Static variables with final keyword

| By Webner

When to use instance variables, static variables and when to use final with them?

Instance variables belong to the object and each object has its own value for each instance variable.

For example:

The company has many employees and each employee has different properties like name, emp_id, address etc so these properties should be defined as instance variables.

On the other hand, static variables should be used for a property which has same value for each object.

For example: Company Name

Each employee in a company will share same company name. So company name should be static:

class Employee {
private int empId;
private String name;
public static String companyName = "ABC Incorporation";

Final for instance variables and Static variables

We can attach final to an instance variable when its value, once assigned, cannot change. For example, empId can be a fixed value hence this instance variable should have final associated with it:

final int empId;
Assign each employee different empId.

Final with static variable can be used where static variable value will not change. For example companyName variable in above example can be a static final variable.

Leave a Reply

Your email address will not be published. Required fields are marked *