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.
thisKeyword: Refers to the current instance of the class.
π» Code example
java Standardpublic 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
thisinside astaticmethod (static methods belong to the class, not an instance). - Null Initialization: Not initializing object references, leading to
NullPointerException.