OOP Note
OOP Note
🚀
A Comprehensive Guide
For example, a Car class might have properties like color, make, and model, and
behaviors like start(), accelerate(), and brake().
When you write Car myCar = new Car();, you're essentially saying: "Build me a
new car based on the Car blueprint, and call it myCar."
1
public class MyClass {
// This is a constructor!
public MyClass() {
// Initialization code goes here
}
}
Constructors don't have an explicit return type. Why? Because their implicit
return type is the instance of the class itself! So, when a constructor finishes its
job, a fully initialized object of its class is ready to be used. Constructors are
fundamentally involved in object creation at run time.
● Instance Variables: These belong to each instance (object) of the class. For
example, color for a Car object. Each car can have a different color. They are
typically initialized to their default values (e.g., 0 for numbers, null for
objects, false for booleans) if not explicitly assigned.
● Static Variables: These are like shared resources. A static member variable
belongs to the class itself, not to any specific object. There's only one copy of
a static variable, no matter how many objects you create. They are initialized
to zero (or their default equivalent) when the class is first loaded, which
usually happens when the first object of its class is created or when a static
member is accessed. Think of a static variable as a shared whiteboard for all
objects of that class. 📋
2
public class MyClass {
static int classCounter = 0; // Static variable
int objectId; // Instance variable
}
● Local Variables: These are declared inside methods or blocks and only exist
within that scope.
● External Variables: This term is more common in C/C++ for global
variables. In Java, global variables are not directly supported in the same
way; instead, you would use public static members.
3
1.6 Initialization: Constructor's Helping Hand 🔧
When an object is created, it needs to be initialized. This crucial task is
automatically performed by the constructor function. It ensures that your
object starts its life in a valid and usable state.
4
Chapter 2: The Four Pillars of OOP 🏛️
OOP is built upon four fundamental principles that make software design more
organized, flexible, and maintainable.
● Data Hiding: The internal state of an object (its member variables) is hidden
from direct external access. This is achieved using access modifiers like
private.
● Controlling Access: You provide public methods (getters and setters) to
allow controlled access to the internal data. This way, you can validate
inputs and ensure the object's integrity.
● Hiding Complexity: Encapsulation also hides the complex internal
workings of an object, presenting a simple interface to the user. You don't
need to know how the car engine works to drive the car!
5
public class BankAccount {
private double balance; // Hidden data
public double getBalance() { // Controlled access
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
Imagine a remote control for your TV. You press the "Volume Up" button, and the
volume increases. You don't need to know the intricate electronic signals sent to
the TV; you just care about the functionality.
● Abstract Classes: These are classes that cannot be instantiated directly (you
can't create objects of an abstract class). They can have both abstract
(without a body) and concrete (with a body) methods. If a class has at least
one abstract method, the class itself must be declared abstract. Abstract
methods must be implemented by subclasses. You cannot declare abstract
constructors.
● Interfaces: These are blueprints for classes, providing a set of methods that
6
a class must implement. They represent a contract. All methods in an
interface are implicitly public and abstract. All variables in an interface are
implicitly public, static, and final. Interfaces specify what a class must do,
but not how it does it. A class uses the implements keyword to adopt an
interface. A class can implement multiple interfaces, allowing for "multiple
parent interfaces."
// Abstract Class
public abstract class Shape {
public abstract double getArea(); // Abstract method (no
body)
public void display() {
System.out.println("This is a shape.");
}
}
// Interface
public interface Drawable {
void draw(); // Implicitly public and abstract
}
public class Circle extends Shape implements Drawable {
// Must implement both abstract methods
@Override
public double getArea() { return 0; }
@Override
public void draw() { }
}
7
class) to inherit properties and behaviors from another class (the superclass or
base class). This promotes code reusability1 – you don't have to write the same
code again and again. Think of it as passing down traits from parents to
children.
Types of Inheritance:
8
class Animal {
void eat() { System.out.println("eating..."); }
}
class Dog extends Animal { // Dog inherits from Animal
void bark() { System.out.println("barking..."); }
}
// In main:
// Dog myDog = new Dog();
// myDog.eat(); // Inherited method
// myDog.bark();
Types of Polymorphism:
3
● Run-time Polymorphism (Method Overriding): This occurs when a
subclass provides a specific implementation for a method that is already
defined in its superclass. The decision of4 which method to call is made at
9
run5 time based on the actual object type. This is extensively used in
implementing inheritance.
class Animal {
void makeSound() { System.out.println("Animal makes a
sound"); }
}
class Dog extends Animal {
@Override
void makeSound() { System.out.println("Woof!"); }
}
// In main:
// Animal myAnimal = new Dog();
// myAnimal.makeSound(); // Calls Dog's makeSound()
10
Chapter 3: Mastering Java's Keywords and Concepts 🔑
Java comes with a rich set of keywords and built-in functionalities that support
OOP principles.
For an interface, public is the only access specifier that can be used directly for
the interface itself. Its members are implicitly public.
12
○ java.net: Networking classes.
● Can contain letters, digits, underscores (_), and dollar signs ($).
● Must start with a letter, underscore, or dollar sign (cannot start with a
digit).6
● Case-sensitive.
● Cannot be a Java keyword (like public, static, void, int).
● Example of a valid identifier: Hour3. An invalid one: 3hour (starts with a
digit).
13
Chapter 4: Handling the Unexpected: Exceptions
💥
Programs don't always run smoothly. Sometimes, unexpected events occur that
disrupt the normal flow of execution. These events are called exceptions. Java's
robust exception handling mechanism helps you manage these disruptions
gracefully.
14
○ Checked Exceptions: All other exceptions under Exception (like
IOException). These must be handled (either caught or declared to be
thrown) by your code.
// Simplified Hierarchy:
// Throwable
// ├── Error
// └── Exception
// ├── RuntimeException
// └── IOException (Example of a checked exception)
● try: A try block contains the code that might throw an exception.
● catch: A catch block immediately follows a try block and specifies the type
of exception it can handle. If an exception of that type (or a subclass of it) is
thrown in the try block, the catch block's code is executed.
● finally: A finally block always executes, regardless of whether an exception
was thrown or caught. It's often used for cleanup operations (e.g., closing
files, releasing resources).
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("This always runs.");
}
15
4.4 Throwing Exceptions: throw and throws 📣
● throw: This keyword is used to generate (throw) an exception explicitly from
within a method.
throw new IllegalArgumentException("Invalid input!");
16
Chapter 5: Building User Interfaces: Java GUI 🖥️
Java provides powerful toolkits for building graphical user interfaces (GUIs).
17
● Event Listener: An object that "listens" for and handles events.
18
Chapter 6: Concurrency: Threads and Multithreading
🚀🚀
Multithreading is a powerful concept that allows a program to perform multiple
tasks concurrently, improving efficiency and responsiveness. Imagine juggling
multiple tasks at once without dropping any balls!
19
The run() method contains the code that the thread will execute. The start()
method is used to begin the execution of a thread. Calling start() indirectly calls
the run() method.
notify() method or the notifyAll() method for this object,8 or until a specified
amount of time has elapsed. When a thread calls wait(), it releases the lock
on the object.
● notify() / notifyAll(): Used to wake up threads that are waiting on an object's
monitor.
● yield(): Hints to the scheduler that the current thread is willing to give up its
current use of a processor.
● join(): Waits for a thread to die. If thread A calls threadB.join(), thread A will
pause its execution until thread B completes.
20
can be platform-dependent. Two threads can have the same priority.
21
Chapter 7: String Manipulation and Utility Classes ✂️
Strings are fundamental in Java, and the language provides robust ways to work
with them.
23
Chapter 8: File I/O: Reading and Writing Data 📂
Java's java.io package provides classes for input and output operations,
including file handling.
24
Chapter 9: Java Development Environment & Tools 🛠️
9.1 Compilation and Execution: From Code to Action ⚙️
● Java Source Code: Written in .java files.
● Compilation: Java source code is compiled into bytecode (.class files) by the
javac tool ( Java compiler).
○ To compile: javac filename.java
● Execution: The Java Virtual Machine ( JVM) executes the bytecode. The java
tool ( Java application launcher) is used to run compiled Java code.
○ To run: java filename (without the .class extension)
25
Chapter 10: Advanced Topics and Nuances 🧠
10.1 Anonymous Inner Classes: Classes on the Fly 🌀
An anonymous inner class is a class without a name. It is defined and
instantiated in a single expression. They are often used to implement event
handlers or to create adapter classes.
27
Sources
1. https://github.com/jshiriyev/jshiriyev.github.io
2. https://github.com/JeffMuniz/RawnOldDevel
3. https://dreamcraftify.com/java/oops
4. https://leetcode.com/discuss/interview-question/3828150/oops-cheatshee
t-for-interviews-30-questions
5. https://brainly.in/question/57758571
6. http://www.readmyhelp.com/android-and-java-interview-questions-with
-practical-examples/
7. https://www.scribd.com/document/706991579/Eroju-Java-Anadu-Repu-Ba
va-Antadu
8. https://quizlet.com/891732488/chapter-2-java-exam-1-part-i-flash-cards/
9. https://www.scribd.com/document/484625277/DOC-20190918-WA0019
10.https://github.com/GirishBhuj/LearningSampleCode
11. https://www.ifixmywindows.com/java-course-using-visual-studio-code/
12.http://stackoverflow.com/questions/18579906/java-using-wait-and-notify-
properly-to-pause-thread-execution-from-another-thre
28
Thanks for journeying through these notes
🌿📖 — with heart, Lati ✨🤝
29