Java is an object-oriented language: you model a program as objects that have state (fields) and behaviour (methods). A class is the blueprint; an object is a concrete instance made from it.
Class एक नक्शा है (जैसे "Car" का design) और object उस नक्शे से बनी असली चीज़ (आपकी लाल Swift, मेरी सफ़ेद Nexon)। हर object का अपना data (रंग, नंबर) होता है, पर काम (methods - चलाना, ब्रेक लगाना) सबके एक जैसे होते हैं।
A first class#
Red Swift at 60 km/h White Nexon at 65 km/h Red Swift at 0 km/h
new Car() creates an object on the heap; a and b hold references to two different objects.
In the editor here, extra classes like Car are written in the same file without public. In a real project, each public class goes in its own file (Car.java).
Constructors#
A constructor runs automatically when an object is created and sets up its initial state. It has the same name as the class and no return type:
Mouse - Rs 499.0 (0 in stock) Keyboard - Rs 1299.0 (15 in stock)
- Overloaded constructors offer different ways to create objects.
this.fieldrefers to the current object's field (needed when a parameter has the same name).this(...)calls another constructor of the same class (must be the first statement).- If you write no constructor, Java provides a default empty one.
Access modifiers and encapsulation#
| Modifier | Class | Package | Subclass | Everywhere |
|---|---|---|---|---|
private |
✓ | |||
| (default) | ✓ | ✓ | ||
protected |
✓ | ✓ | ✓ | |
public |
✓ | ✓ | ✓ | ✓ |
Encapsulation = make fields private and expose controlled public methods (getters/setters) that can validate data:
Farah earns 83600.0 Invalid salary for Farah, keeping 83600.0
toString, equals and object references#
Every class inherits from Object. Overriding toString() controls how the object prints:
a = (2, 3) a == b: false a.equals(b): true a == c: true
If you override equals, also override hashCode - HashMap and HashSet depend on both being consistent.
static members#
A static field is shared by all objects of the class; a static method belongs to the class and is called as ClassName.method():
Order#1 Rs 499.0 Order#2 Rs 1299.5 Order#3 Rs 250.0 3 orders, sales Rs 2048.5
A static method cannot use instance fields directly (there is no this) - that is why main cannot touch non-static fields without creating an object.
Records - compact data classes (Java 16+)#
For classes that only carry data, a record generates the constructor, getters, equals, hashCode and toString for you:
Course[code=CS202, title=Java Programming, credits=4] Java Programming has 4 credits true
Summary#
- A class defines fields and methods;
newcreates objects; variables hold references. - Constructors initialise objects; overload them and chain with
this(...). - Encapsulation:
privatefields + validatedpublicgetters/setters. - Override
toString(andequals/hashCodetogether);staticmembers are shared by the class. recordcreates immutable data classes in one line.