Java – Instance Variables

Instance Variables:

  • Defining a variable inside the class and outside to methods.
  • Instance variables get memory inside every object and initializes with default values.

this:

  • It is a keyword and pre-defined instance variable in java.
  • It is also called Default Object Reference Variable.
  • “this-variable” holds object address.
    • this = object_address;
  •  It is used to access object inside the instance methods and constructor.

Parameterized constructor:

  • Constructor with parameters is called Parametrized constructor.
  • We invoke the constructor in every object creation process.
  • Parameterized constructor is used to set initial values to instance variables in Object creation process.

Note: We invoke the constructor with parameter values in object creation as follows

class Test
{
            int a;
            Test(int a)
            {
                        this.a = a;
            }
            public static void main(String[] args)
            {
                        Test obj = new Test(10); // pass value while invoking constructor
            }
}

Program to create two Employee objects with initial values:

class Employee
{
            int id;
            String name;
            double salary;
            Employee(int id, String name, double salary)
            {
                        this.id = id;
                        this.name = name;
                        this.salary = salary;
            }
            void details()
            {
                        System.out.println(“Emp ID is : ” + this.id);
                        System.out.println(“Emp Name is : ” + this.name);
                        System.out.println(“Emp Salary is : ” + this.salary);
            }
            public static void main(String[] args)
            {
                        Employee e1 = new Employee(101, “Amar”, 5000);
                        Employee e2 = new Employee(102, “Annie”, 8000);
                        e1.details();
                        e2.details();
            }
}
Scroll to Top