How to use variables within classes in Java
Using variables within classes in Java is fundamental to object-oriented programming. Variables in Java classes are often referred to as fields or member variables. They hold data that characterizes the state of objects created from the class. Here’s a small article with code examples to illustrate how to use variables within classes in Java.
Declaring variables in a class
In Java, we declare variables within a class by specifying their type and name. These variables can have different access modifiers, such as public, private, or protected, to control their visibility and accessibility.
public class Student {// Instance variables (also known as member variables or fields)private String name;private int age;// Constructor to initialize the variablespublic Student(String name, int age) {this.name = name;this.age = age;}// Getter methods to access the variablespublic String getName() {return name;}public int getAge() {return age;}}
In this example, the Student class has two instance variables: name and age. They are declared as private to encapsulate the data and ensure controlled access.
Using variables in objects
To use these variables, we create objects of the class and access them using dot notation.
public class Main {public static void main(String[] args) {// Creating a Student objectStudent student1 = new Student("Alice", 20);// Accessing variables using getter methodsString studentName = student1.getName();int studentAge = student1.getAge();// Printing the informationSystem.out.println("Student Name: " + studentName);System.out.println("Student Age: " + studentAge);}}
In this Main class, we create a Student object student1 and use the getName() and getAge() methods to retrieve the values of name and age. This encapsulation ensures that the variables are accessed through controlled methods.
Modifying variables
We can also modify the variables within the class using setter methods.
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;}// Getter methods to access member variablespublic String getName() {return name;}public int getAge() {return age;}}
We can then use these setter methods to change the values of the variables:
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;}// Getter methods to access member variablespublic String getName() {return name;}public int getAge() {return age;}}
In this way, we can encapsulate and control the access to variables within classes in Java, promoting good software design practices.
Free Resources