Notes › OOP
Classes, Objects, Constructors and Access Modifiers
Class vs object
- A class is a blueprint: it defines fields (state) and methods (behaviour). No memory for data is used until you create objects.
- An object is an instance of the class with its own copy of the fields.
class Student {
String name; // field (instance variable)
int marks;
void show() { System.out.println(name + ": " + marks); } // method
}
Student s1 = new Student(); // object 1
Student s2 = new Student(); // object 2 — independent of s1
s1.name = "Aman"; s1.marks = 91;
Memory (Java): s1 (the reference) lives on the stack; the object itself lives on the heap. Student s3 = s1; copies the reference — both point to the same object.
| Class | Object | |
|---|---|---|
| What | blueprint / template | real instance |
| Memory | loaded once | allocated per object (heap) |
| Created by | class keyword |
new |
| Count | one | many |
Constructors
A special method that initialises a new object. Same name as the class, no return type, called automatically by new.
Default constructor
If you write no constructor, the compiler adds an empty no-argument one. Fields get default values (0, false, null). Once you write any constructor, the default one is not added.
Parameterized constructor
class Student {
private String name;
private int marks;
Student(String name, int marks) {
this.name = name; // this.name = field, name = parameter
this.marks = marks;
}
}
Constructor overloading and chaining
class Student {
private String name; private int marks;
Student() { this("Unknown", 0); } // calls the 2-arg constructor
Student(String name) { this(name, 0); }
Student(String name, int marks) { this.name = name; this.marks = marks; }
}
this(...) / super(...) must be the first statement. A child constructor always calls a parent constructor first (implicitly super()).
Copy constructor
Creates a new object as a copy of another.
Student(Student other) { this.name = other.name; this.marks = other.marks; }
In C++ the compiler gives a default copy constructor that does a shallow copy — write your own when the class owns pointers (deep copy; see the Rule of Three).
class Box {
int* data;
public:
Box(int v) : data(new int(v)) {} // initializer list
Box(const Box& o) : data(new int(*o.data)) {} // deep copy
~Box() { delete data; } // destructor
};
Private constructor
Stops others from creating objects — used for Singleton and utility classes.
class Config {
private static final Config INSTANCE = new Config();
private Config() {}
public static Config get() { return INSTANCE; }
}
Constructor vs method
| Constructor | Method | |
|---|---|---|
| Name | same as class | any |
| Return type | none | required (or void) |
| Called | automatically by new |
explicitly |
| Inherited | no | yes |
Destructors and cleanup
- C++:
~ClassName()runs automatically when the object goes out of scope or is deleted — release memory, files, locks (RAII). - Java: no destructors; the garbage collector frees unreachable objects. Use
try-with-resources/close()for files and connections (finalize()is deprecated). - Python:
__del__exists but usewith(context managers) for cleanup.
this and super
this→ the current object: resolve name clashes, pass yourself, chain constructors.super→ the parent: call the parent's constructor or an overridden method (super.sound()).
static vs instance members
class Student {
static int count = 0; // ONE copy shared by all objects
String name; // each object has its own
Student(String n) { name = n; count++; }
static int total() { return count; } // called as Student.total()
}
| static | instance | |
|---|---|---|
| Belongs to | the class | each object |
| Access | ClassName.member |
obj.member |
Can use this? |
no | yes |
| Can access instance fields directly? | no | yes |
Static blocks run once when the class loads. main is static so the JVM can call it without an object.
Access modifiers
Java
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
private |
✅ | ❌ | ❌ | ❌ |
| default (none) | ✅ | ✅ | ❌ | ❌ |
protected |
✅ | ✅ | ✅ | ❌ |
public |
✅ | ✅ | ✅ | ✅ |
A top-level class can only be public or default.
C++
private (default in class), protected, public (default in struct). friend functions/classes can access private members. Inheritance mode (public/protected/private) further limits access.
Python
No enforcement: name public, _name "internal, please don't touch", __name name-mangled to _ClassName__name. Use @property for controlled access:
class Student:
def __init__(self, marks):
self._marks = marks
@property
def marks(self): return self._marks
@marks.setter
def marks(self, v):
if not 0 <= v <= 100: raise ValueError("0–100 only")
self._marks = v
Getters and setters
Read and write private fields with validation. Don't add a setter for fields that shouldn't change.
Immutable class (Java)
public final class Point { // can't be subclassed
private final int x, y; // set once
public Point(int x, int y) { this.x = x; this.y = y; }
public int getX() { return x; } // no setters
public int getY() { return y; }
}
Rules: final class, private final fields, no setters, defensive copies of mutable fields. String is immutable — that's what makes it safe to share and cache. Java record Point(int x, int y) {} does all of this in one line.
Interview one-liners
- Class = blueprint; object = instance on the heap.
- Constructors have no return type and aren't inherited;
this()/super()must come first. - Static members belong to the class; instance members to each object.
protected= package + subclasses; default = package only.- Related: Four Pillars of OOP, Java OOP Concepts.