Classes and Objects in Java
In this lesson: Create classes and objects in Java — fields, methods, new keyword and multiple objects — with output. In Hindi & English.
What are classes and objects
Java is object-oriented, so everything is built from classes and objects. A class is a blueprint that describes data and behaviour. An object is a real thing made from that blueprint. "Car" is a class; your specific car is an object.
new.Defining a class
class Car {
String color; // field (data)
int speed; // field (data)
void drive() { // method (action)
System.out.println(color + " car driving");
}
}
A class groups related data (fields like color) and actions (methods like drive). This blueprint does nothing on its own until we create an object from it.
Creating an object
Car c = new Car(); // create an object c.color = "Red"; // set its data c.speed = 80; c.drive(); // call its method
The new keyword builds an object from the class. c holds a reference to it, and we use the dot (.) to set fields and call methods.
Fields and methods
- Fields (instance variables) store the object's data —
color,speed. - Methods are what the object can do —
drive(). - You reach both with the dot operator:
c.color,c.drive().
Together, fields and methods describe what an object knows and can do.
Many objects, own data
Car a = new Car(); a.color = "Red"; Car b = new Car(); b.color = "Blue"; a.drive(); // Red car driving b.drive(); // Blue car driving
Blue car driving
Each object made from the class has its own fields. a and b are separate cars with separate colours — changing one does not affect the other.
Methods that use fields
class Student {
String name;
int marks;
void result() {
String r = (marks >= 40) ? "Pass" : "Fail";
System.out.println(name + ": " + r);
}
}
// use:
Student s = new Student();
s.name = "Aman"; s.marks = 75;
s.result();
A method can read the object's own fields (via this implicitly). Here result() uses name and marks to decide pass or fail for that student.
Common mistakes
- Forgetting
new. A class is only a blueprint; you neednewto make an object. - Using fields without an object. Non-static fields belong to an object, reached via the object.
- File vs class name. A public class must match the file name.
- Confusing class and object. The class is the design; the object is the actual thing.
Summary
- A class is a blueprint of fields (data) and methods (actions).
- An object is a real instance made with
new. - Access fields and methods with the dot operator.
- Each object keeps its own copy of the fields.
- Classes and objects are the foundation of OOP in Java.
Next, set up objects with Java constructors, or reuse code with inheritance.
Frequently Asked Questions
What is the difference between a class and an object?
How do I create an object in Java?
new keyword with the class name: Car c = new Car();. This creates an object in memory and stores a reference to it in c, which you then use to access its fields and methods.