Create Class and Object in Java
beginner· OOP · Classes & Objects
Problem
A class is a blueprint describing what fields and methods its objects will have; an object is a concrete instance created from that blueprint, with its own copy of the fields.
Define a Student class with a name and age, then create an object from it and print its details.
Input
name = "Aditi", age = 20
Output
Student: Aditi, Age: 20
Java Program
Java
class Student {
String name;
int age;
}
public class CreateClassAndObject {
public static void main(String[] args) {
Student student = new Student(); // allocates a new Student object
student.name = "Aditi";
student.age = 20;
System.out.println("Student: " + student.name + ", Age: " + student.age);
}
}Output
Student: Aditi, Age: 20
Core Logic
Declaring the class's fields first, then creating an object with new and assigning values to those fields, separates the blueprint from any one instance of it.
How It Works
- 1
class Studentdeclares the blueprint, withnameandageas its fields. - 2
new Student()allocates a new object in memory, distinct from any other Student that might exist. - 3
student.name = "Aditi";andstudent.age = 20;set that one object's fields directly. - 4Printing the object's fields reads back exactly what was assigned to it.
Creating one Student object and setting its fields to
"Aditi" and 20 prints "Student: Aditi, Age: 20".💡
Key Point: The class itself holds no data — every field value lives on the object created from it, which is why the same class can produce many objects with completely different field values.
Key Concepts
classobjectnew keywordfields