← Back to Chapters

Java Class & Object

? Java Class & Object

? Quick Overview

In Java, a class is a blueprint that defines properties and behaviors, while an object is a real-world instance created from that class. Together, they form the foundation of Object-Oriented Programming (OOP).

? Key Concepts

  • Class Blueprint or template
  • Object Instance of a class
  • Fields Variables inside a class
  • Methods Functions inside a class

? Syntax / Theory

A class is defined using the class keyword. Objects are created using the new keyword, which allocates memory at runtime.

? Code Example

? View Code Example
// Defining a class in Java
class Student {
String name;
int age;

void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

// Main class to create object
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Rahul";
s1.age = 20;
s1.display();
}
}

? Live Output / Explanation

Output

Name: Rahul
Age: 20

The Student object s1 accesses class variables and methods using the dot (.) operator.

? Interactive: Class vs. Object Factory

Define the Class properties below, then click "new Car()" to create Objects.

(No objects created yet...)

✅ Tips & Best Practices

  • Always name classes using PascalCase
  • One public class per file
  • Use meaningful object names
  • Encapsulate data using access modifiers

? Try It Yourself

  • Create a class Car with fields and a method
  • Create multiple objects of the same class
  • Print different values for each object