Last Updated : 05 Aug, 2025
Try it on GfG Practice
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities.
A class in Java is a template with the help of which we create real-world entities known as objects that share common characteristics and properties.
Here, the below Java code demonstrates the basic use of class in Java. It defines a Student
class with two instance variables (id
and n
), creates an object s1 and prints values of s1.
// File: Student.java
class Student {
int id;
String n;
// Added constructor to initialize both fields
public Student(int id, String n) {
this.id = id;
this.n = n;
}
}
// File: Main.java
public class Main {
public static void main(String[] args) {
// Creating Student object using the new constructor
Student s1 = new Student(10, "Alice");
System.out.println(s1.id);
System.out.println(s1.n);
}
}
Properties of Java Classes
access_modifier class<class_name> {
data member;
method;
constructor;
nested class;
interface
;
}
Components of Java Classes
In general, class declarations can include these components, in order:
Objects are the instances of a class that are created to use the attributes and methods of a class. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of:
Objects correspond to things found in the real world. For example, a graphics program may have objects such as "circle", "square", and "menu". An online shopping system might have objects such as "shopping cart", "customer", and "product".
Object Instantiation (Declaring Objects)Note: Objects (non-primitive types) are always allocated on the heap, while their reference variables are stored on the stack.
When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.
Java Object DeclarationAs we declare variables like (type name). This notifies the compiler that we will use the name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variables , the type must be strictly a concrete class name. In general, we can't create objects of an abstract class or an interface.
Dog tuffy
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object.
Initializing a Java ObjectThe new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.
Java
// Java Program to Demonstrate the
// use of a class with instance variable
// Class Declaration
public class Dog {
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed, int age,
String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
// method 1
public String getName() {
return name;
}
// method 2
public String getBreed() {
return breed;
}
// method 3
public int getAge() {
return age;
}
// method 4
public String getColor() {
return color;
}
@Override public String toString()
{
return ("Name is: " + this.getName()
+ "\nBreed, age, and color are: "
+ this.getBreed() + "," + this.getAge()
+ "," + this.getColor());
}
public static void main(String[] args)
{
Dog tuffy
= new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Name is: tuffy Breed, age, and color are: papillon,5,white
Explanation:
Dog tuffy = new Dog("tuffy","papillon",5, "white");
The result of executing this statement can be illustrated as :
Initialize Object by using Method/Function JavaNote: All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent's no-argument constructor (as it contains only one statement i.e super();), or the Object class constructor if the class has no other parent (as the Object class is the parent of all classes either directly or indirectly).
// Java Program to initialize Java Object
// by using method/function
public class Geeks {
static String name;
static float price;
static void set(String n, float p) {
name = n;
price = p;
}
static void get()
{
System.out.println("Software name is: " + name);
System.out.println("Software price is: " + price);
}
public static void main(String args[])
{
Geeks.set("Visual studio", 0.0f);
Geeks.get();
}
}
Software name is: Visual studio Software price is: 0.0Ways to Create an Object of a Class
There are four ways to create objects in Java. Although the new keyword is the primary way to create an object, the other methods also internally rely on the new keyword to create instances.
1. Using new KeywordIt is the most common and general way to create an object in Java.
Java
// creating object of class Test
Test t = new Test();
2. Using Reflection (Dynamic Class Loading)
Reflection is a powerful feature in Java that allows a program to inspect and modify its own structure and behavior at runtime.
Java
// Assume Student class exists (or show its definition)
class Student {
public Student() {}
}
public class Main {
public static void main(String[] args) {
try {
Class<?> c = Class.forName("Student");
Student s2 = (Student) c.getDeclaredConstructor().newInstance();
System.out.println("Object created: " + s2);
} catch (ClassNotFoundException e) {
System.err.println("Class not found!");
} catch (NoSuchMethodException e) {
System.err.println("No default constructor!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: Reflection is used in frameworks like Spring for dependency injection.
3. Using clone() methodThe clone() method is present in the Object class. It creates and returns a copy of the object.
Java
// creating object of class Test
Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)t1.clone();
Example:
Java
// Creation of Object
// Using clone() method
// Main class
// Implementing Cloneable interface
class Geeks implements Cloneable {
// Method 1
@Override
protected Object clone()
throws CloneNotSupportedException
{
// Super() keyword refers to parent class
return super.clone();
}
String name = "GeeksForGeeks";
// Method 2
// main driver method
public static void main(String[] args)
{
Geeks o1 = new Geeks();
// Try block to check for exceptions
try {
Geeks o2 = (Geeks)o1.clone();
System.out.println(o2.name);
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
4. Deserialization
De-serialization is a technique of reading an object from the saved state in a file. Refer to Serialization/De-Serialization in Java.
Java
import java.io.*;
class Student implements Serializable {
private String name;
public Student(String name) { this.name = name; }
@Override public String toString()
{
return "Student: " + name;
}
}
public class Main {
public static void main(String[] args)
{
// Serialization
try (ObjectOutputStream out
= new ObjectOutputStream(
new FileOutputStream("student.ser"))) {
out.writeObject(new Student("Alice"));
}
catch (IOException e) {
e.printStackTrace();
}
// Deserialization
try (ObjectInputStream in = new ObjectInputStream(
new FileInputStream("student.ser"))) {
Student s = (Student)in.readObject();
System.out.println(s); // Output: Student: Alice
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Creating Multiple Objects by one type only (A good practice)Note: The class must implement serializable.
In real-time, we need different objects of a class in different methods. Creating a number of references for storing them is not a good practice and therefore we declare a static reference variable and use it whenever required. In this case, the wastage of memory is less. The objects that are not referenced anymore will be destroyed by the Garbage Collector of Java.
Example:
Java
Test test = new Test();
test = new Test();
In the inheritance system, we use a parent class reference variable to store a sub-class object. In this case, we can switch into different subclass objects using the same referenced variable.
Example:
Java
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
public class Test {
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
}
Anonymous Objects in Java
Anonymous objects are objects that are instantiated without storing their reference in a variable. They are used for one-time operations (e.g., method calls) and are discarded immediately after use.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) { launch(args); }
@Override public void start(Stage stage)
{
Button button = new Button("Click Me");
button.setOnAction(
event
-> System.out.println(
"Button clicked!")); // Anonymous object via
// lambda
StackPane root = new StackPane(button);
stage.setScene(new Scene(root, 300, 200));
stage.show();
}
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4