What is a variable, field, property in Java?


In programming to hold data members we use variables, Java you can declare three types of variables namely,

  • Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
  • Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  • Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword.

In addition to these, they are referred with different names based on the usage.

Fields − Variables of a class i.e. instance variables and static variables are called fields. They can’t be abstract except this you can use any other modifier with fields.

Example

public class Sample{
   int data = 90;
   static data = 145;
}

Property

In general, fields with private modifier, setter and getter methods are considered as properties.

public class Sample{
   private int name;
   public String getName(){
      return this.number;
   }
   public void setName(String name){
      this.name = name;
   }
}

Example

public class Student{
   private String name;
   private int age;
   public Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getName() {
      return this.name;
   }
   public int getAge() {
      return this.age;
   }
   public static void main(String[] args){
      Student std = new Student("Krishna", 29);
      System.out.println(std.getName());
      System.out.println(std.getAge());
   }
}

Output

Krishna
29

Updated on: 06-Aug-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements