These are the notes for CS Fundamentals for Placements, episode 12, the first of three episodes on object-oriented programming (OOP), the most asked topic in placement interviews. You invent it one problem at a time: procedural vs object-oriented programming, class, object, instance, fields (attributes) and methods, state and behaviour; constructors (default, parameterized, copy), constructor overloading, the this keyword; encapsulation, data hiding, getters and setters; the four access modifiers (public, private, protected, default/package); static members; the object on the heap vs the reference on the stack; and the destructor (C++) vs Java's garbage collector. Every term is explained in plain words, and there is a full glossary at the end. All outputs and error messages below are real: the Java programs were compiled and run with javac/java 21, the C++ program with g++ 13.3.
A quick refresher of Java basics used here: a variable is a named box holding a value (int balance = 5000;); int is a whole number and String is text; an array is a numbered row of boxes of one type (int[] balances = {5000, 200}, where balances[0] is 5000); a method (a function) is a named block of code you can call, with parameters (its inputs) and a return type (what it gives back, void = nothing); System.out.println(x) prints x on its own line; every Java program starts in public static void main(String[] args) inside a class; a program is first compiled by javac (which reports compile errors) and then run by java (which can throw runtime exceptions).
The five problems
| Problem | What it teaches |
|---|---|
| Data falls out of sync | Procedural vs OOP, class, object, instance, fields, methods, state, behaviour, new, the dot operator |
| Half-built objects | Default values, null, constructor, parameterized constructor, shadowing, this, overloading, chaining with this(...), copy constructor, the default constructor |
| Anyone can break the data | private, encapsulation, data hiding, getters, setters, access modifiers |
| A count every object shares | Instance vs static fields, static methods |
| Where objects live | Stack, heap, references, == on objects, copying, destructor, garbage collection |
Problem 1: data falls out of sync (classes and objects)
A small bank stores each customer's name and balance. The simple way is one array per detail, where customer i is position i in every array. Writing code as a list of steps (functions) that work on separate data like this is procedural programming.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// procedural: one array per piece of data
String[] names = {"Riya", "Aman", "Kabir"};
int[] balances = {5000, 200, 1200};
Arrays.sort(balances); // sort by balance...
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + ": " + balances[i]);
}
}
}
Output:
Riya: 200
Aman: 1200
Kabir: 5000
Riya had 5000. We sorted one array and not the other, so names and balances drifted apart. No error, no crash, silently wrong data. Every new detail (phone, address, PAN) is one more array to keep in sync by hand. These are called parallel arrays, and they are a classic source of bugs.
The fix: keep each customer's data together
| At a bank branch | In Java |
|---|---|
| The blank account-opening form: lists what every customer must fill | Class: a blueprint that says which data and actions every object of this kind has |
| Riya's filled-in form | Object (an instance of the class): one real thing made from the class |
| The boxes on the form: name, balance | Fields (attributes, member variables): variables inside each object. Their current values = the object's state |
| Deposit, withdraw | Methods (member functions): functions that belong to the object and work on its fields = its behaviour |
Object-oriented programming (OOP) builds programs out of objects that bundle state and behaviour together.
class Account {
String name; // fields = state
int balance;
void deposit(int amount) { // method = behaviour
balance += amount;
}
}
public class Main {
public static void main(String[] args) {
Account riya = new Account(); // an object
riya.name = "Riya";
riya.balance = 5000;
riya.deposit(500);
System.out.println(riya.name + ": " + riya.balance);
}
}
Output:
Riya: 5500
class Account { ... }defines the blueprint. Nothing exists in memory yet.new Account()creates an object (allocates memory for its fields) and gives back a reference to it.Account riyais a variable of typeAccountthat refers to that object.- The dot operator reaches inside an object:
riya.name,riya.deposit(500). - Inside
deposit,balancemeans this object's balance. Two accounts each have their ownbalance.
| Procedural | Object-oriented |
|---|---|
| Data and functions are separate | Data and the code that uses it live together in a class |
| Functions take the data as arguments | Objects carry their own data; you call methods on them |
| Good for small scripts | Scales to large programs with many kinds of things |
| Example: C | Examples: Java, C++, Python, C# |
Problem 2: half-built objects (constructors and this)
The failing attempt: setting fields by hand
class Account {
String name;
int balance;
}
public class Main {
public static void main(String[] args) {
Account aman = new Account();
aman.balance = 200; // forgot to set the name
System.out.println(aman.name + ": " + aman.balance);
}
}
Output:
null: 200
Java gives every field a default value: 0 for numbers, false for boolean, '\u0000' for char, and null (meaning "refers to no object") for references such as String. The object exists but is half-built.
The fix: the constructor
A constructor is a special method that runs automatically every time an object is created with new, to set it up. In Java it has the same name as the class and no return type (not even void). A constructor that takes parameters is a parameterized constructor.
The trap: shadowing
class Account {
String name;
int balance;
Account(String name, int balance) { // constructor
name = name; // which name?
balance = balance;
}
}
public class Main {
public static void main(String[] args) {
Account aman = new Account("Aman", 200);
System.out.println(aman.name + ": " + aman.balance);
}
}
Output:
null: 0
It compiles and still saves nothing. Inside the constructor, the parameter name shadows (hides) the field name: the nearest declaration wins. So name = name copies the parameter onto itself.
this, overloading, chaining and the copy constructor
this means the current object: the one being built (in a constructor) or the one the method was called on. this.name is the field; plain name is the parameter.
class Account {
String name;
int balance;
Account(String name, int balance) {
this.name = name; // this = the object
this.balance = balance;
}
Account(String name) { // overloaded: starts at 0
this(name, 0);
}
Account(Account other) { // copy constructor
this(other.name, other.balance);
}
}
public class Main {
public static void main(String[] args) {
Account aman = new Account("Aman", 200);
Account kabir = new Account("Kabir");
Account copy = new Account(aman);
System.out.println(aman.name + ": " + aman.balance);
System.out.println(kabir.name + ": " + kabir.balance);
System.out.println(copy.name + ": " + copy.balance);
}
}
Output:
Aman: 200
Kabir: 0
Aman: 200
- Constructor overloading: several constructors with the same name but different parameter lists. Java picks one from the arguments you pass (overloading = same name, different parameters).
- Constructor chaining:
this(...)calls another constructor of the same class. It must be the first statement in the constructor. It avoids repeating the set-up code. - Copy constructor: builds a new object with the same values as an existing one. (C++ creates one automatically; Java does not, you write it yourself.)
The default constructor disappears
If a class has no constructor at all, Java quietly adds a default constructor with no parameters (that's why new Account() worked in Problem 1). As soon as you write any constructor, the free one is gone:
class Account {
String name;
int balance;
Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account(); // worked before. Now?
}
}
Compiler output:
Main.java:13: error: constructor Account in class Account cannot be applied to given types;
Account a = new Account(); // worked before. Now?
^
required: String,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Want both? Write Account() { } yourself (a no-argument constructor).
| Constructor kind | What it is | Java | C++ |
|---|---|---|---|
| Default | No parameters, added automatically if you write none | Yes | Yes |
| No-argument (written) | No parameters, written by you | Account() { } |
Account() { } |
| Parameterized | Takes values to set up the object | Account(String n, int b) |
same |
| Copy | Builds a copy of another object | write it yourself | generated automatically: Account(const Account&) |
Problem 3: anyone can break the data (encapsulation)
The failing attempt: open fields
class Account {
String name;
int balance;
Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
}
public class Main {
public static void main(String[] args) {
Account riya = new Account("Riya", 5000);
riya.balance = -90000; // anyone can do this
System.out.println(riya.name + ": " + riya.balance);
}
}
Output:
Riya: -90000
Any line in any file can do this, and in a big program you would never find which one did.
The fix: private fields behind checking methods
| A bank | Encapsulation |
|---|---|
| Cash is behind the counter; customers can't walk in | private fields: only the class's own code can touch them |
| The cashier checks every slip | Methods with checks: withdraw() validates before changing anything |
| The passbook shows the balance; you can't edit it | Getter: a method that returns a field's value |
class Account {
private String name; // hidden from outside
private int balance;
Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
void withdraw(int amount) {
if (amount <= 0 || amount > balance) {
System.out.println("Rejected: " + amount);
return;
}
balance -= amount;
}
int getBalance() { return balance; } // getter
}
public class Main {
public static void main(String[] args) {
Account riya = new Account("Riya", 5000);
riya.withdraw(95000);
riya.withdraw(1000);
System.out.println("Balance: " + riya.getBalance());
riya.balance = -90000;
}
}
Compiler output:
Main.java:25: error: balance has private access in Account
riya.balance = -90000;
^
1 error
With that last line deleted, the program runs:
Rejected: 95000
Balance: 4000
- Encapsulation: bundling data with the methods that work on it, and controlling access to the data through those methods.
- Data hiding: the "hide the fields" part of encapsulation (making them
private). - Getter (accessor): a method that returns a field, e.g.
getBalance(). - Setter (mutator): a method that changes a field after checking the new value, e.g.
setName(String n)that rejects an empty name. - Benefits: invalid states are impossible from outside; if the rules change, you edit one method; the inside can change without breaking code that uses the class.
Access modifiers in Java
An access modifier is a keyword that decides who may use a class, field, method or constructor. A package is a named folder of related classes (java.util is a package).
| Modifier | Same class | Same package | Child class in another package | Any other code |
|---|---|---|---|---|
public |
Yes | Yes | Yes | Yes |
protected |
Yes | Yes | Yes | No |
| default (no keyword, "package-private") | Yes | Yes | No | No |
private |
Yes | No | No | No |
Child classes come from inheritance (next episode). The usual rule: fields private, and only the methods others need public. C++ has public, protected and private (members of a C++ class are private by default; of a struct, public), and no package level.
Problem 4: a count every object shares (static)
The failing attempt: an instance field
class Account {
String name;
int count = 0; // how many accounts opened?
Account(String name) {
this.name = name;
count++;
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account("Riya");
Account b = new Account("Aman");
Account c = new Account("Kabir");
System.out.println(a.count + " " + b.count
+ " " + c.count);
}
}
Output:
1 1 1
A normal field is an instance field: one copy per object. Each account counted only itself.
The fix: static
A static field (class variable) belongs to the class itself: exactly one copy, shared by all objects (like one notice board in the corridor instead of a photocopy in every room). A static method belongs to the class and is called on the class name, with no object needed.
class Account {
String name;
static int count = 0; // ONE copy, shared by the class
Account(String name) {
this.name = name;
count++;
}
static int opened() { return count; }
}
public class Main {
public static void main(String[] args) {
new Account("Riya");
new Account("Aman");
new Account("Kabir");
int n = Account.opened(); // via the class
System.out.println("Accounts opened: " + n);
}
}
Output:
Accounts opened: 3
A static method has no current object, so it can't use this or instance fields directly:
class Account {
String name;
static int count = 0;
static void show() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
Account.show();
}
}
Compiler output:
Main.java:5: error: non-static variable name cannot be referenced from a static context
System.out.println(name);
^
1 error
That is also why main is static: the JVM calls it before any object exists.
Problem 5: where objects live (stack, heap, references)
The failing attempt: b = a as a backup
class Account {
String name;
int balance;
Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account("Riya", 5000);
Account b = a; // a "copy"?
b.balance = 0;
System.out.println("a: " + a.balance);
System.out.println(a == b);
}
}
Output:
a: 0
true
Stack and heap
- The stack is the memory area for each method call's local variables. It is cleaned up automatically when the method returns.
- The heap is a large memory area for objects, which may outlive the method that created them.
newalways creates the object on the heap. - The variable
a(on the stack) doesn't hold the object; it holds the object's address, called a reference. Like a house address written on a slip of paper. Account b = a;copies the slip, not the house: both refer to the same object (they are aliases).==on objects compares references (same object?), not contents.- For a real, separate copy:
new Account(a)(a copy constructor).
STACK HEAP
+--------+ +-------------------+
| a ----+----------> | Account |
| b ----+----------> | name = "Riya" |
+--------+ | balance = 0 |
+-------------------+
Using a reference that is null fails at run time:
Account b = null;
System.out.println(b.name);
Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "<local2>" is null
at Main.main(Main.java:12)
(<local2> is how the JVM names a local variable when the class was compiled without debug information.)
How objects die: destructor vs garbage collector
A destructor (C++) is a method named ~ClassName() that runs automatically when an object is destroyed, to release what it holds (close a file, free memory). A local object is destroyed when its block (the { } it was declared in) ends.
#include <iostream>
#include <string>
using namespace std;
class Account {
string name;
public:
Account(string n) : name(n) {
cout << "open " << name << endl;
}
~Account() { // destructor
cout << "close " << name << endl;
}
};
int main() {
Account riya("Riya");
{
Account aman("Aman");
cout << "inside the block" << endl;
} // aman dies here
cout << "end of main" << endl;
} // riya dies here
Output:
open Riya
open Aman
inside the block
close Aman
end of main
close Riya
Objects are destroyed in reverse order of creation. (: name(n) is a C++ initializer list: it sets the field before the constructor body runs.)
Java has no destructors. The garbage collector (GC), part of the JVM, finds objects that no reference points to any more ("garbage") and frees their memory at a time it chooses. You never free memory by hand in Java, but you can't predict exactly when an object goes away; for files and connections Java uses try-with-resources / close() instead. (finalize() exists in old Java but is deprecated and should not be used.)
Common mistakes (and the real output)
| Mistake | Real output | Fix |
|---|---|---|
| Parallel arrays, sorting only one | Riya: 200 (she had 5000) |
One class, an array/list of objects |
name = name; in a constructor |
null: 0 |
this.name = name; |
new Account() after writing Account(String, int) |
error: constructor Account in class Account cannot be applied to given types; |
Write Account() { } yourself |
| Writing a private field from outside | error: balance has private access in Account |
Call a method such as withdraw() |
| A shared counter as an instance field | 1 1 1 |
static int count |
| Instance field used in a static method | error: non-static variable name cannot be referenced from a static context |
Make the method non-static, or pass an object in |
Account b = a; as a backup |
a: 0 |
new Account(a) (copy constructor) |
Using a null reference |
java.lang.NullPointerException: Cannot read field "name" because "<local2>" is null |
Create the object first, or check for null |
Giving a "constructor" a return type: void Account() { System.out.println("set up!"); } |
new Account() prints nothing: it compiles, but void Account() is an ordinary method, so Java used the default constructor |
Constructors have no return type |
Mini project: a tiny bank
Everything from this episode in one class: private fields, final fields (assigned once, never changed), overloaded and chained constructors, validation that throws an exception (stops object creation with an error), methods with checks, getters, a static counter and static method, and toString() (the method Java calls to turn an object into text when you print it).
// mini project: a tiny bank with encapsulated accounts
class Account {
private static int opened = 0; // shared by all accounts
private final int number; // set once, never changes
private final String owner;
private int balance;
Account(String owner, int balance) {
if (owner == null || owner.isEmpty()) {
throw new IllegalArgumentException("owner is required");
}
opened++;
this.number = 1000 + opened; // 1001, 1002, ...
this.owner = owner;
this.balance = Math.max(0, balance);
}
Account(String owner) { this(owner, 0); }
boolean deposit(int amount) {
if (amount <= 0) return false;
balance += amount;
return true;
}
boolean withdraw(int amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
boolean transferTo(Account other, int amount) {
if (other == this || !withdraw(amount)) return false;
other.deposit(amount);
return true;
}
int getBalance() { return balance; }
String getOwner() { return owner; }
static int getOpened() { return opened; }
public String toString() { // how an Account prints
return "#" + number + " " + owner + ": " + balance;
}
}
public class Main {
public static void main(String[] args) {
Account riya = new Account("Riya", 5000);
Account aman = new Account("Aman");
System.out.println(riya + " | " + aman);
System.out.println("transfer 1500: " + riya.transferTo(aman, 1500));
System.out.println("transfer 9999: " + riya.transferTo(aman, 9999));
System.out.println("deposit -50 : " + aman.deposit(-50));
System.out.println(riya + " | " + aman);
System.out.println("accounts opened: " + Account.getOpened());
try {
new Account("");
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
Output:
#1001 Riya: 5000 | #1002 Aman: 0
transfer 1500: true
transfer 9999: false
deposit -50 : false
#1001 Riya: 3500 | #1002 Aman: 1500
accounts opened: 2
rejected: owner is required
Note: transferTo reaches other's private balance through other.deposit(...), and could even touch other.balance directly: private means private to the class, not to one object.
Practice
- Add a
deposit()that rejects amounts ≤ 0. - Add a
setName()that rejects an empty name. - Count the accounts created with a balance above 1000, using
static. - Predict:
Account c = new Account(a); c.balance = 0;What isa's balance? Isa == c? - What are the default values of an
int, abooleanand aStringfield? - A class has only
Account(String n). Doesnew Account()compile? Why? - Why can't a static method use
this? - Which access modifier lets classes in the same package, but nowhere else, use a field?
- Draw the stack and heap after
Account a = new Account("Riya", 5000); Account b = new Account(a); Account c = b;. - In the C++ demo, add a third object inside the inner block. In which order do the destructors print?
- Is
privateper object or per class? Explain withtransferTo. - Give two benefits of encapsulation.
Solutions
Questions 1 to 4 in one Java 21 program:
class Account {
private String name;
private int balance;
static int rich = 0; // Q3: accounts with balance > 1000
Account(String name, int balance) {
this.name = name;
this.balance = balance;
if (balance > 1000) rich++;
}
Account(Account other) { this(other.name, other.balance); }
boolean deposit(int amount) { // Q1
if (amount <= 0) {
System.out.println("Rejected deposit: " + amount);
return false;
}
balance += amount;
return true;
}
void setName(String name) { // Q2
if (name == null || name.isEmpty()) {
System.out.println("Rejected empty name");
return;
}
this.name = name;
}
void setBalanceForTest(int b) { balance = b; }
int getBalance() { return balance; }
String getName() { return name; }
}
public class Main {
public static void main(String[] args) {
Account a = new Account("Riya", 5000);
a.deposit(0);
a.deposit(250);
a.setName("");
System.out.println(a.getName() + ": " + a.getBalance());
new Account("Aman", 200);
new Account("Kabir", 1200);
System.out.println("rich accounts: " + Account.rich);
Account c = new Account(a); // Q4
c.setBalanceForTest(0);
System.out.println("a: " + a.getBalance() + " c: " + c.getBalance() + " same object? " + (a == c));
}
}
Output:
Rejected deposit: 0
Rejected empty name
Riya: 5250
rich accounts: 2
a: 5250 c: 0 same object? false
(The copy c starts at 5250, so it too counts as rich: after that line Account.rich is 3.)
akeeps its balance;a == cis false: the copy constructor made a separate object.0,false,null.- No. Writing any constructor removes the default one; you get "constructor Account in class Account cannot be applied to given types".
- A static method runs without any object, so there is no "current object" for
thisto mean. - Default (no modifier, package-private).
- Stack:
a,b,c. Heap: two Account objects.a→ object 1;bandc→ object 2 (a copy of object 1). - Reverse order of creation inside the block: the third object closes first, then Aman, then (at the end of
main) Riya. - Per class. Code inside
Accountmay access the private fields of anyAccountobject, e.g.other.balanceintransferTo. - Invalid states can't be created from outside (every change is checked); the inside can change (rules, representation) without breaking the code that uses the class.
Quick quiz
class Box {
int n;
static int s;
Box() { n++; s++; }
}
// in main:
Box a = new Box(); Box b = new Box();
System.out.println(b.n + " " + Box.s);
- A. 1 1
- B. 2 2
- C. 1 2
- D. 2 1
Answer
C, 1 2. n is an instance field: each Box has its own, so b.n is 1. s is static: one shared copy that counted both boxes, so 2.
Interview questions
- What is OOP? How is it different from procedural programming? OOP organises a program as objects that bundle data (state) with the methods that act on it (behaviour). Procedural code keeps data and functions separate.
- Class vs object? A class is a blueprint/type; an object is an instance created from it, with its own field values.
- What is a constructor? How is it different from a method? Code that runs automatically on
newto initialise an object; same name as the class, no return type, can't be called like a normal method. - Types of constructors? Default, no-argument, parameterized, copy (and in C++, move constructors).
- What happens to the default constructor when you write your own? Java no longer adds it.
- What is constructor overloading? Chaining? Several constructors with different parameter lists; one calling another with
this(...)as its first statement. - What does
thisrefer to? The current object. Used to tell fields from parameters, to pass the current object, and to chain constructors. - What is encapsulation? Data hiding? Bundling data with its methods and controlling access through them; data hiding is making the fields private.
- Why use getters and setters instead of public fields? Setters can validate; the internal representation can change without breaking callers; read-only fields can have only a getter.
- Java access modifiers and their scope? public (everywhere), protected (package + subclasses), default (package), private (class).
- What is a static member? One that belongs to the class rather than to each object: one shared copy (fields) or callable without an object (methods).
- Why is
mainstatic? The JVM calls it before any object of the class exists. - Where are objects and references stored in Java? Objects on the heap; local variables holding references on the stack.
- What does
b = ado for objects? How do you copy an object? Copies the reference (both names point to one object). Use a copy constructor (or a copy method). ==vs.equals()for objects?==compares references;.equals()compares contents when the class defines it (e.g.String).- Does Java have destructors? No. The garbage collector frees unreachable objects; resources are released with
close()/ try-with-resources. C++ has destructors (~ClassName()).
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Procedural programming | Programs as step-by-step functions working on separate data | parallel arrays names[], balances[] |
| Parallel arrays | Several arrays where index i describes one thing; easy to break | sorting only balances |
| Object-oriented programming (OOP) | Programs built from objects that bundle state and behaviour | Account objects |
| Class | Blueprint describing the fields and methods of a kind of object | the blank account form |
| Object | One real thing made from a class, with its own field values | Riya's account |
| Instance | Another word for an object of a class | riya is an instance of Account |
| Field / attribute | A variable inside each object | balance |
| Method | A function that belongs to a class/object | deposit(500) |
| State | The current values of an object's fields | balance = 5500 |
| Behaviour | What an object can do: its methods | deposit, withdraw |
new |
Creates an object on the heap and returns a reference to it | new Account("Aman", 200) |
| Dot operator | Reaches a field or method of an object | riya.name |
| Default value | The value a field gets if you don't set it | 0, false, null |
null |
A reference that points to no object | null: 200 |
| Constructor | Special method run automatically by new to set up an object |
Account(String n, int b) |
| Default constructor | No-parameter constructor Java adds only if you write none | new Account() in Problem 1 |
| Parameterized constructor | A constructor that takes values | new Account("Aman", 200) |
| Copy constructor | Builds a new object with the same values as another | new Account(aman) |
| Overloading | Same name, different parameter lists | three Account(...) constructors |
| Constructor chaining | One constructor calling another with this(...) |
this(name, 0) |
| Shadowing | A local name hides a field with the same name | name = name does nothing |
this |
The current object | this.name = name |
| Encapsulation | Bundling data with its methods and controlling access through them | private balance + withdraw() |
| Data hiding | Making fields inaccessible from outside | private int balance |
| Getter / accessor | Method returning a field's value | getBalance() |
| Setter / mutator | Method changing a field after checking | setName("") rejected |
| Access modifier | Keyword controlling who can use a member | public, protected, private |
public |
Usable from any code | public class Main |
private |
Usable only inside its own class | private int balance |
protected |
Usable in the same package and in child classes | for inheritance (next episode) |
| Default / package-private | No keyword: usable only in the same package | String name; |
| Package | A named group (folder) of related classes | java.util |
| Instance field | One copy per object | int count → 1 1 1 |
| Static field (class variable) | One copy shared by the whole class | static int count → 3 |
| Static method | Belongs to the class, called without an object | Account.opened() |
| Static context | Code with no current object (a static method) | "non-static variable ... static context" |
final field |
Can be assigned only once | private final int number |
| Stack | Memory for method calls' local variables, freed on return | a, b references |
| Heap | Memory area where objects created with new live |
the Account object |
| Reference | A value that points to (holds the address of) an object | Account a |
| Alias | Two references to the same object | b = a |
| NullPointerException | Runtime error from using a null reference |
b.name with b = null |
| Destructor | C++ method ~ClassName() run automatically when an object is destroyed |
close Aman |
| Garbage collector (GC) | JVM part that frees objects no longer referenced | Java's replacement for destructors |
| Initializer list (C++) | Sets fields before the constructor body runs | : name(n) |
toString() |
Method Java uses to turn an object into text | #1001 Riya: 5000 |
| Exception | An error object that stops normal flow until caught | IllegalArgumentException |
Summary
- Parallel arrays drifted apart silently (
Riya: 200), so we bundled state (fields) and behaviour (methods) into a class; each object (instance) carries its own data. - Fields default to 0/false/null, so objects came out half-built (
null: 200). A constructor runs onnew;thisfixes shadowing (null: 0); overloading, chaining withthis(...)and copy constructors follow. Writing any constructor removes the default one. - Open fields allowed
-90000. private fields behind checking methods, getters and setters give encapsulation and data hiding; four access modifiers set who sees what. - An instance counter printed
1 1 1; a static field is one shared copy (3), and static methods have nothis. b = acopies a reference: objects live on the heap, references on the stack;==compares references; copy with a copy constructor.- C++ destructors run when an object dies (reverse order of creation); Java uses the garbage collector.
Next episode: OOP 2: inheritance and polymorphism. A savings account is an account plus interest: reuse a class without copy-paste, override methods, and let one call do different things for different objects.