Core Module
12 min forge

Java Classes & Objects

The foundations of Java OOPs, constructors, and 'this' keyword.

Java Classes & Objects

πŸ“˜ What is it

A Class in Java is a template or blueprint used to create objects. An Object is an instance of a class that has state (variables) and behavior (methods).

πŸ—οΈ Key Components

  • Fields/Variables: Data associated with the class.
  • Methods: Logic/Behavior of the class.
  • Constructors: Special methods called when an object is instantiated.
  • this Keyword: Refers to the current instance of the class.

πŸ’» Code example

java Standard
public class Person { String name; int age; // Constructor public Person(String name, int age) { this.name = name; this.age = age; } public void display() { System.out.println(name + " is " + age + " years old."); } public static void main(String[] args) { Person p1 = new Person("Alice", 25); // Creating an object p1.display(); } }

❌ Common mistakes

  • Default Constructor: Forgetting that Java provides a default constructor ONLY if no other constructors are defined.
  • Static vs Instance: Attempting to use this inside a static method (static methods belong to the class, not an instance).
  • Null Initialization: Not initializing object references, leading to NullPointerException.