English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
When using data variables to save data members in programming, Java can declare three types of variables, namely:
Local variables-Variables defined within methods, constructors, or blocks are called local variables. This variable will be declared and initialized within the method, and the variable will be destroyed after the method completes.
Instance Variables-Instance variables are variables in a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from any method, constructor, or block within the specific class.
Class (Static) Variables-Class variables are variables declared within a class using the static keyword outside any method.
In addition to these, use different names for reference based on usage.
Fields-Variables of a class, that is, instance variables and static variables, are called fields. They cannot be abstract unless you can use other modifiers with fields.
public class Sample{ int data = 90; static data = 145; }
Generally, fields with the private modifier and setter and getter methods are considered properties.
public class Sample{ private int name; public String getName(){ return this.number; } public void setName(String name){ this.name = name; } }
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 Result
Krishna 29