Class Members in Java
-
Last Updated: February 16, 2025
-
By: javahandson
-
Series
Learn Java in a easy way
Learn about class members in Java, including fields, methods, constructors, static variables, static methods, and nested classes. Understand their roles, usage, and key differences with clear explanations and examples.
Class members are the building blocks of a class in Java. They define what a class contains and what it can do. In simple terms, class members represent both the state (data) and behavior (functionality) of an object.
Every class is made up of different types of members who work together to create a complete structure. These members allow a class to store values, perform operations, and even define internal structures.
In Java, class members are mainly categorized as:
Understanding class members is essential because they form the foundation of object-oriented programming. Once you understand how these elements work together, designing and working with classes becomes much easier.
Instance variables represent the state of an object and are used to store its data. They are declared inside a class but outside any method, constructor, or block. These variables define the properties of an object, such as a person’s name, age, or an account’s balance.
One important characteristic of instance variables is that they belong to an object, not to the class itself. This means that every time a new object is created, a separate copy of instance variables is also created in memory. As a result, each object can store different values independently.
For example, two Employee Objects can have different names and salaries even though they are created from the same class.
private, public, or protectedWhen an object is created using the new keyword, memory is allocated in the heap, and all instance variables are automatically initialized with default values:
int, double, etc. → 0boolean → falsenullUnlike local variables, instance variables are available throughout the class and can be accessed by all instance methods. This makes them essential for maintaining and manipulating an object’s state.
In real-world terms, instance variables help us model objects more naturally. For example, each Student object can have its own name, rollNumber, and marks, even though all students belong to the same class structure.
Example: Student Class with Instance Variables
class Student {
// Instance variables
String name;
int rollNumber;
double marks;
// Method to display student details
void display() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
}
}
public class Main {
public static void main(String[] args) {
// Creating first object
Student s1 = new Student();
s1.name = "Suraj";
s1.rollNumber = 101;
s1.marks = 85.5;
// Creating second object
Student s2 = new Student();
s2.name = "Shweta";
s2.rollNumber = 102;
s2.marks = 92.0;
// Displaying data
s1.display();
System.out.println("-----");
s2.display();
}
}
In this example, name, rollNumber, and marks are instance variables. They represent the state of each Student object.
s1 and s2 are two different objectss1.name does not affect s2.nameOutput:
Name: Suraj Roll Number: 101 Marks: 85.5 ----- Name: Shweta Roll Number: 102 Marks: 92.0
Methods define the behavior of objects. They specify what actions an object can perform. In simple terms, if instance variables represent an object’s data, methods define how that data is used or manipulated.
A method is a block of code that is executed when it is called. Methods are declared inside a class and can perform operations such as calculations, updating values, or displaying information. They play a key role in making a class functional and interactive.
One important feature of methods is that they can access and modify instance variables. This allows objects to change their state over time. For example, a Student object may have a method to update marks or display details.
Methods can also take input and return output, depending on how they are defined:
void) → perform action onlyExample: Methods in Student Class
class Student {
String name;
int marks;
// Method to set data
void setData(String n, int m) {
name = n;
marks = m;
}
// Method to display data
void display() {
System.out.println("Name: " + name);
System.out.println("Marks: " + marks);
}
// Method to check result
String getResult() {
if (marks >= 40) {
return "Pass";
} else {
return "Fail";
}
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setData("Suraj", 85);
s.display();
System.out.println("Result: " + s.getResult());
}
}
In this example, methods define what actions the Student object can perform:
setData() → assigns values to instance variablesdisplay() → prints student detailsgetResult() → returns pass/fail based on marksThis shows that methods not only perform actions but also interact with the object’s data to produce meaningful results.
Constructors are special members of a class used to initialize objects when they are created. Whenever an object is created using the new keyword, a constructor is automatically called to set up the object’s initial state.
A constructor has the same name as the class and does not have any return type (not even void). Its main purpose is to assign values to instance variables and ensure the object is ready to use immediately after creation.
Unlike regular methods, constructors are called automatically at object creation and are not invoked explicitly.
void)In Java, constructors are mainly categorized into two types:
A default constructor is automatically provided by Java if no constructor is defined in the class. It takes no parameters and initializes instance variables to default values.
int → 0boolean → falsenullIf you define your own constructor, Java will not provide the default constructor automatically.
A parameterized constructor is used to initialize objects with specific values at the time of creation. It allows you to pass arguments while creating the object, making initialization more flexible and meaningful.
Example: Constructors in Student Class
class Student {
String name;
int marks;
// Default constructor
Student() {
name = "Unknown";
marks = 0;
}
// Parameterized constructor
Student(String n, int m) {
name = n;
marks = m;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Marks: " + marks);
}
}
public class Main {
public static void main(String[] args) {
// Using default constructor
Student s1 = new Student();
// Using parameterized constructor
Student s2 = new Student("Suraj", 90);
s1.display();
System.out.println("-----");
s2.display();
}
}
In this example:
Student() → initializes object with default valuesStudent(String n, int m) → initializes object with given valuesEach time an object is created, the corresponding constructor is called automatically.
Constructors ensure that objects are created in a valid and usable state. They remove the need to manually set values after object creation and help in writing cleaner and more reliable code.
Static variables are variables that belong to the class rather than to any specific object. They are declared using the static keyword and are shared across all instances of the class. This means that instead of each object having its own copy, there is only one common copy of a static variable.
Static variables are useful when you want to represent data that is common to all objects. For example, if all students belong to the same school, the school name can be declared as a static variable.
Another important point is that static variables are initialized only once when the class is loaded into memory. After that, all objects use the same shared value unless it is explicitly changed.
static keywordExample: Static Variable in Student Class
class Student {
String name;
int rollNumber;
// Static variable
static String schoolName = "ABC School";
void display() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("School: " + schoolName);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Suraj";
s1.rollNumber = 101;
Student s2 = new Student();
s2.name = "Shweta";
s2.rollNumber = 102;
s1.display();
System.out.println("-----");
s2.display();
}
}
In this example:
If the value is changed using one object, it affects all objects
schoolName is a static variables1 and s2 share the same value of schoolNameFor example:
Student.schoolName = "XYZ School";
Now both s1 and s2 will reflect the updated value.
Static methods are methods that belong to the class rather than to any specific object. They are declared using the static keyword and can be called without creating an instance of the class.
Unlike instance methods, static methods do not operate on a specific object’s data. Instead, they work with class-level data (static variables) or perform general utility operations.
Static methods are commonly used for functionality that does not depend on object state, such as utility methods, calculations, or helper functions.
static keywordStatic methods have some important restrictions:
This happens because static methods are loaded at class level, while instance variables belong to objects created later.
Example: Static Methods in Student Class
class Student {
String name;
int marks;
static String schoolName = "ABC School";
// Static method
static void showSchool() {
System.out.println("School: " + schoolName);
}
// Instance method
void display() {
System.out.println("Name: " + name);
System.out.println("Marks: " + marks);
}
// Static method accessing instance data via object
static void showStudentDetails(Student s) {
System.out.println("Name: " + s.name);
System.out.println("Marks: " + s.marks);
}
}
public class Main {
public static void main(String[] args) {
// Calling static method using class name
Student.showSchool();
Student s1 = new Student();
s1.name = "Suraj";
s1.marks = 90;
// Calling instance method
s1.display();
// Static method accessing instance data via object
Student.showStudentDetails(s1);
}
}
Understanding the Example
showSchool() → static method accessing static variabledisplay() → instance method accessing instance variablesshowStudentDetails(Student s) → static method accessing instance data using object referenceThis clearly shows that static methods can work with instance data, but only when an object is explicitly provided. Static methods are useful when behavior does not depend on object-specific data. They provide a way to define class-level functionality and are commonly used for utility operations.
Nested classes are classes that are defined inside another class. They help in logically grouping related classes together, making the code more organized and easier to maintain.
In many real-world scenarios, a class is only relevant within the context of another class. Instead of creating a separate top-level class, we can define it inside another class as a nested class.
Nested classes improve code readability, encapsulation, and help in keeping related functionality together.
In Java, nested classes are mainly divided into two types:
a. Inner Classes (Non-Static Nested Classes)
An inner class is a non-static class defined inside another class. It is closely associated with an instance of the outer class.
One of the key advantages of inner classes is that they can access all members of the outer class, including private variables and methods.
Key points:
static keywordExample: Inner Class
class Outer {
int x = 10;
class Inner {
void display() {
System.out.println("Value of x: " + x);
}
}
}
public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
b. Static Nested Classes
A static nested class is declared with the static keyword inside another class. Unlike inner classes, it does not depend on an instance of the outer class.
It behaves more like a regular class but is logically grouped inside another class.
Key points:
static keywordExample: Static Nested Class
class Outer {
static int x = 20;
static class Inner {
void display() {
System.out.println("Value of x: " + x);
}
}
}
public class Main {
public static void main(String[] args) {
Outer.Inner inner = new Outer.Inner();
inner.display();
}
}
Key Differences Between Inner and Static Nested Classes
In this article, we explored class members in Java and understood how they form the foundation of any class. Instance variables store the state of an object, methods define its behavior, and constructors ensure proper initialization. Static variables and static methods provide shared data and functionality at the class level, while nested classes help organize related logic within a single structure.
A clear understanding of class members in Java helps you write cleaner, more maintainable, and efficient code. These concepts are not only important for beginners but are also frequently used in real-world applications and interviews.
If you are learning Java or preparing for interviews, mastering class members in Java is a must. It strengthens your object-oriented programming fundamentals and helps you design better applications.
That’s all about class members in Java. If you have any questions, feel free to ask in the comments section. If you found this article useful, consider sharing it with your friends and colleagues to help them learn as well.