DEV Community

Karthick Narayanan
Karthick Narayanan

Posted on

Day 2: Understanding Class and Object in Java

1. Class in Java

What is a Class?

  • A class is a blueprint or template used to create objects.
  • A class is a logical entity (it does not occupy memory by itself).
  • A class is called a logical entity because it only defines structure and behavior, and memory is allocated only when an object is created.
  • class is a Java keyword.

=> Syntax of a Class

class ClassName {

}
Enter fullscreen mode Exit fullscreen mode

Rules for Class Name

  • The first letter should be uppercase.
  • A class name can contain:

    • Alphabets (A–Z, a–z)
    • Digits (0–9)
    • Special characters _ (underscore) and $ (dollar sign)
  • Digits are allowed, but:

    • ❌ Not at the beginning
    • ✅ Allowed in the middle or at the end

Valid class names

class MobileShop
class Mobile_Shop
class Mobile$Shop
class MobileShop2
Enter fullscreen mode Exit fullscreen mode

Invalid class names

class 2MobileShop   // starts with a number
class Mobile-Shop   // hyphen not allowed
Enter fullscreen mode Exit fullscreen mode

2. Object in Java

What is an Object?

  • An object is a real‑world (physical) entity.
  • An object is an instance of a class because it is a real thing created using the class blueprint and stored in memory.
  • Object occupies memory.

=> Object Syntax

ClassName referenceName = new ClassName();
Enter fullscreen mode Exit fullscreen mode

Example:

MobileShop mobile = new MobileShop();
Enter fullscreen mode Exit fullscreen mode

Object Characteristics

  • An object is a combination of:

    • State → variables / data
    • Behaviour → methods / actions
  • new Keyword

    • new is a Java keyword.
  • When we use new:

    • JVM allocates memory in the Heap area at runtime.
    • A new object is created.

  • Real‑World Example

    • Class → MobileShop (blueprint)
    • Object → Actual mobile shop (real instance)

We can create multiple objects from a single class.


  • Summary

    • Class → Blueprint, logical, no memory
    • Object → Real entity, physical, occupies memory
    • new keyword → Creates object and allocates heap memory

Top comments (0)