Class Definition
Defining a Class in Java
A class is a blueprint for creating objects. It defines the properties (fields) and behaviors (methods) that objects of that class will have.
Basic Class Structure
public class Car {
// Fields (instance variables)
String make;
String model;
int year;
double speed;
// Methods
public void accelerate() {
speed += 10;
}
public void brake() {
speed = Math.max(0, speed - 10);
}
public String getInfo() {
return year + " " + make + " " + model;
}
}
Access Modifiers
public class Person {
public String name; // Accessible everywhere
protected int age; // Accessible in same package and subclasses
String email; // Package-private (default)
private String password; // Accessible only within this class
public void publicMethod() { }
protected void protectedMethod() { }
void defaultMethod() { }
private void privateMethod() { }
}
Static vs Instance Members
public class Counter {
// Instance variable - each object has its own
int count;
// Static variable - shared among all objects
static int totalCount;
// Instance method - called on an object
public void increment() {
count++;
totalCount++;
}
// Static method - called on the class
public static int getTotalCount() {
return totalCount;
}
}
Getters and Setters
public class Student {
private String name;
private int age;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String name) {
this.name = name;
}
// Getter with validation
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 0 && age <= 150) {
this.age = age;
}
}
}
Creating Objects
Object Creation
Using the new Keyword
// Create object using new
Car myCar = new Car();
// Initialize fields
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2024;
myCar.speed = 0;
// Call methods
myCar.accelerate();
System.out.println(myCar.speed); // 10
Object Reference
// Object variable is a reference
Car car1 = new Car();
Car car2 = car1; // car2 references same object as car1
car1.make = "Toyota";
System.out.println(car2.make); // "Toyota" (same object!)
// Creating new object
Car car3 = new Car();
car3.make = "Honda";
System.out.println(car1.make); // "Toyota" (different object)
Multiple Objects
// Each new creates a separate object
Car car1 = new Car();
Car car2 = new Car();
// car1 and car2 are different objects
car1.make = "Toyota";
car2.make = "Honda";
System.out.println(car1.make); // "Toyota"
System.out.println(car2.make); // "Honda"
Object Methods
// Calling methods
Car myCar = new Car();
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2024;
// Pass objects as parameters
public void printCarInfo(Car car) {
System.out.println(car.year + " " + car.make + " " + car.model);
}
// Return objects from methods
public Car createCar(String make, String model) {
Car car = new Car();
car.make = make;
car.model = model;
return car;
}
Garbage Collection
// Objects are automatically garbage collected
public void createObjects() {
Car car = new Car();
car.make = "Toyota";
// car goes out of scope here
// Object is eligible for garbage collection
}
// Explicitly making object eligible
Car car = new Car();
car = null; // Now eligible for GC
Null References
Car car = null; // Reference points to nothing
// car.make = "Toyota"; // NullPointerException!
if (car != null) {
car.make = "Toyota"; // Safe
}
Instance Variables
Instance Variables
Instance variables are fields that belong to each object (instance) of a class.
Declaration and Initialization
public class Employee {
// Instance variables
String name;
int age;
double salary;
boolean active;
// With default values
String department = "Engineering";
int yearsOfService = 0;
}
Default Values
public class DefaultValues {
// Primitive types
int i; // 0
double d; // 0.0
boolean b; // false
char c; // '\u0000'
long l; // 0L
float f; // 0.0f
byte bt; // 0
short s; // 0
// Object references
String str; // null
Object obj; // null
int[] arr; // null
}
Instance vs Local Variables
public class Comparison {
int instanceVar = 10; // Instance variable
public void method() {
int localVar = 20; // Local variable
// Instance variable accessible here
System.out.println(instanceVar); // 10
// Local variable accessible here
System.out.println(localVar); // 20
}
public void anotherMethod() {
// Cannot access local variable from other method
// System.out.println(localVar); // COMPILE ERROR!
// Can access instance variable
System.out.println(instanceVar); // 10
}
}
Scope and Lifetime
public class ScopeExample {
int instanceVar; // Lives as long as object exists
public void method() {
int localVar; // Lives only during method execution
for (int i = 0; i < 10; i++) {
int loopVar; // Lives only during loop iteration
}
// loopVar not accessible here
}
// localVar not accessible here
}
// instanceVar still accessible as long as object exists
Initialization Order
public class InitOrder {
// 1. Instance variables initialized (in declaration order)
int a = 10;
String s = "hello";
// 2. Instance initializer block
{
System.out.println("Instance initializer");
}
// 3. Constructor runs
public InitOrder() {
System.out.println("Constructor");
}
}
This Reference
The this Keyword
this is a reference to the current object - the object whose method or constructor is being called.
Disambiguating Variables
public class Person {
private String name;
private int age;
public Person(String name, int age) {
// this.name = instance variable
// name = parameter
this.name = name;
this.age = age;
}
}
Returning Current Object
public class Builder {
private String name;
private int value;
public Builder setName(String name) {
this.name = name;
return this; // Returns current object
}
public Builder setValue(int value) {
this.value = value;
return this;
}
}
// Method chaining
Builder builder = new Builder()
.setName("test")
.setValue(42);
Passing this as Parameter
public class EventListener {
public void register(EventSource source) {
source.addListener(this); // Pass current object
}
}
public class EventSource {
private List<EventListener> listeners = new ArrayList<>();
public void addListener(EventListener listener) {
listeners.add(listener);
}
}
this() for Constructor Chaining
public class Rectangle {
private int width;
private int height;
private String color;
public Rectangle() {
this(10, 10); // Call constructor with parameters
}
public Rectangle(int width, int height) {
this(width, height, "black");
}
public Rectangle(int width, int height, String color) {
this.width = width;
this.height = height;
this.color = color;
}
}
this in Inner Classes
public class Outer {
private int outerVar = 10;
public class Inner {
private int outerVar = 20; // Shadows outer's outerVar
public void printVars() {
System.out.println(outerVar); // 20 (inner's)
System.out.println(this.outerVar); // 20 (inner's)
System.out.println(Outer.this.outerVar); // 10 (outer's)
}
}
}
Practice Problems
Design a data structure that supports adding words and searching for them.
Example:
Input: addWord("bad"), addWord("dad"), search("bad")
Output: true
Word was added and found
Optimal Solution — O(n) for add, O(26^n) for search with dots time, O(n * m) space
Use Trie data structure for efficient word storage and search.
class WordDictionary {
private WordDictionary[] children;
private boolean isEnd;
public WordDictionary() {
children = new WordDictionary[26];
isEnd = false;
}
public void addWord(String word) {
WordDictionary node = this;
for (char c : word.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) {
node.children[idx] = new WordDictionary();
}
node = node.children[idx];
}
node.isEnd = true;
}
}Edge Cases:
- Empty word
- Single character
- All dots
Design a HashMap without using built-in hash table libraries.
Example:
Input: MyHashMap map = new MyHashMap(); map.put(1, 1); map.get(1)
Output: 1
Basic HashMap operations
Optimal Solution — O(1) average for put/get time, O(n) space
Use array of linked lists for collision handling.
class MyHashMap {
private static class Entry {
int key, value;
Entry next;
Entry(int key, int value) {
this.key = key;
this.value = value;
}
}
private Entry[] buckets;
private int size;
public MyHashMap() {
buckets = new Entry[16];
size = 0;
}
}Edge Cases:
- Collision handling
- Resize when full
- Remove non-existent
Design a singly linked list with get, addAtHead, addAtTail, addAtIndex, deleteAtIndex operations.
Example:
Input: addAtHead(1), addAtTail(3), addAtIndex(1, 2), get(1)
Output: 2
Linked list becomes 1->2->3
Optimal Solution — O(n) for get, O(1) for addAtHead time, O(n) space
Use dummy head node to simplify edge cases.
class MyLinkedList {
private class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
private Node dummy;
private int size;
public MyLinkedList() {
dummy = new Node(0);
size = 0;
}
}Edge Cases:
- Empty list
- Add at index 0
- Delete last element
Quiz
1. What is a class in Java?
2. What does the 'new' keyword do?
3. What is the difference between instance and local variables?
4. What does 'this' keyword refer to?
Flashcards
Question
What is the difference between a class and an object?
Click to reveal answer
Answer
A class is a blueprint/template, an object is an instance of that class with actual values.
Question
How do you create an object in Java?
Click to reveal answer
Answer
Use the 'new' keyword: ClassName obj = new ClassName();
Question
What are default values for instance variables?
Click to reveal answer
Answer
0 for numbers, false for boolean, null for objects, '\u0000' for char.
Question
When would you use 'this.name = name' in a constructor?
Click to reveal answer
Answer
When parameter name shadows instance variable name. 'this' disambiguates to refer to instance variable.
Question
What is Classes and Objects?
Click to reveal answer
Answer
Classes and Objects is a key concept in Java programming.
Revision Notes
Key Takeaways
- 1.A class is a blueprint, an object is an instance
- 2.Instance variables belong to each object
- 3.Local variables exist only during method execution
- 4.this refers to the current object
Interview Tips
- •Understand the difference between class and object
- •Know default values for all primitive types
- •Use 'this' to disambiguate variable names
- •Practice designing classes with encapsulation
Cheat Sheet
Cheat Sheet
- Class:
class ClassName { fields; methods; } - Object:
ClassName obj = new ClassName(); - Instance var:
int count;(belongs to object) - Local var:
int x = 5;(belongs to method) - this: reference to current object
- this(): call another constructor