0% found this document useful (0 votes)
3 views30 pages

OOP Note

This document is a comprehensive guide to Object-Oriented Programming (OOP) in Java, covering fundamental concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It explains key features of Java, including constructors, member variables, and access specifiers, while also introducing exception handling. The guide aims to provide a clear understanding of how to effectively utilize OOP principles in Java programming.

Uploaded by

yaredberhanu246
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

OOP Note

This document is a comprehensive guide to Object-Oriented Programming (OOP) in Java, covering fundamental concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It explains key features of Java, including constructors, member variables, and access specifiers, while also introducing exception handling. The guide aims to provide a clear understanding of how to effectively utilize OOP principles in Java programming.

Uploaded by

yaredberhanu246
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

☕Java Object-Oriented Programming

🚀
A Comprehensive Guide

Welcome to the exciting world of Object-Oriented Programming (OOP) in Java!


This guide will take you on a journey through the core principles and powerful
features that make Java a robust and versatile language. Think of OOP as
building with LEGOs: each LEGO brick is an "object," and you combine them to
create something amazing! 🧱

Crafted with ❤️ by a fellow soul — Lati 🌀📝


Chapter 1: The Heart of OOP - Objects and Classes ❤️
At the very foundation of OOP are objects and classes.

1.1 What's a Class? A Blueprint! 🏡


Imagine you're an architect. Before you build a house, you create a detailed
blueprint. In Java, a class is exactly that: a blueprint or a template for creating
objects. It defines the structure (data) and behavior (methods) that all objects of
that class will possess.

For example, a Car class might have properties like color, make, and model, and
behaviors like start(), accelerate(), and brake().

1.2 What's an Object? The House Itself! 🚗


If a class is the blueprint, an object is the actual house built from that blueprint.
An object is an instance of a class. You can create many houses from the same
blueprint, just as you can create many objects from a single class.

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.3 Bringing Objects to Life: Constructors 🛠️


How does an object get created? Through a special method called a constructor.
Think of a constructor as the initial setup crew for your house. When you use
the new keyword, the constructor is automatically called to initialize the newly
created object.

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.

1.4 Member Variables: The Object's Attributes 📊


Inside our class blueprint, we define member variables (also known as fields or
attributes). These are the characteristics or data that describe an object.

●​ 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.

1.5 Static Methods: Class-Level Actions 📢


Just like static variables, static member functions (or methods) belong to the
class, not to an object. You can call them directly using the class name, without
needing to create an object. They are often used for utility functions that don't
depend on the state of a particular object.

public class Calculator {​


public static int add(int a, int b) {​
return a + b;​
}​
}​

// To use it:​
// int result = Calculator.add(5, 3);​

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.

2.1 Encapsulation: The Secure Capsule 💊


Encapsulation is like putting things into a secure capsule. It's the mechanism of
binding code and data together into a single unit (the object) and keeping them
safe from the outside world. This means:

●​ 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;​
}​
}​
}​

2.2 Abstraction: Focusing on What Matters 🗺️


Abstraction is about simplifying complex reality by modeling classes based on
essential properties and behaviors, without including lower-level details. It
focuses on "what" an object does rather than "how" it does it.

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.

In Java, abstraction is achieved using:

●​ 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() { }​
}​

2.3 Inheritance: Building on What Exists 👨‍👩‍👧‍👦


Inheritance is a powerful feature that allows a class (the subclass or derived

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.

●​ The extends keyword is used to inherit a class.


●​ The super keyword is used to refer to members (variables and methods) of
the base class from a subclass, and to call the superclass's constructor.
●​ All classes in Java are ultimately inherited from the java.lang.Object class.
●​ Inheritance relationships are often described as "Is-A" relationships (e.g., a
Dog Is-A Animal).

Types of Inheritance:

●​ Single Inheritance: A class inherits from only one superclass.


●​ Multilevel Inheritance: A child class inherits from a superclass, and that
child class then acts as a superclass for another derived class (e.g.,
Grandparent -> Parent -> Child).
●​ Hierarchical Inheritance: Multiple subclasses inherit from a single
superclass.
●​ Multiple Inheritance: A class inheriting from multiple superclasses directly.
Java does not support multiple inheritance for classes (to avoid the "Diamond
Problem"), but it achieves similar functionality through interfaces.
●​ Hybrid Inheritance: A combination of two or more 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();​

2.4 Polymorphism: Many Forms, One Action 🎭


Polymorphism (meaning "many forms") allows objects of different classes to be
treated as objects of a common type. It enables a single action to be performed
in different ways. Imagine a "Talk" action. A Dog barks, a Cat meows, and a
Human speaks. The "Talk" action takes different forms depending on the object.

Types of Polymorphism:

●​ Compile-time Polymorphism (Method Overloading): This occurs when


there are multiple methods with the same name2 but different parameters
(number, type, or order). The correct method to call is determined at
compile time.​

class Calculator {​
int add(int a, int b) { return a + b; }​
double add(double a, double b) { return a + b; }​
}​

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()​

2.5 Dynamic Binding: Linking at Runtime 🔗


Dynamic binding (also known as late binding) is a feature closely related to
run-time polymorphism. It means that the compiler doesn't know exactly which
method implementation will be called until the program is running. This allows
for flexibility and extensibility.

2.6 Message Passing: Objects Talking to Each Other 🗣️


Message passing describes how objects communicate and interact with each
other. When you call a method on an object (e.g., myCar.start()), you are sending
a "message" to that object, asking it to perform a specific action. This interaction
between objects is a fundamental aspect of OOP.

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.

3.1 The final Keyword: Unchangeable! 🚫


The final keyword in Java signifies immutability or a constant state.

●​ final variable: Once assigned, its value cannot be changed.


●​ final method: Cannot be overridden in its subclasses. This is useful for
ensuring certain behaviors remain consistent. A final method can be
inherited.
●​ final class: Cannot be extended by other classes. This means no class can
inherit from a final class. However, a final class can extend other classes.

3.2 Access Specifiers: Who Can See What? 👀


Access specifiers (or modifiers) control the visibility of classes, members
(variables), and methods.

●​ public: Visible to all classes in the program.


●​ protected: Visible within the same package and to subclasses in any
package. This is a common modifier for interfaces.
●​ private: Only visible within the class where it's declared. This is the strictest
level of encapsulation.
●​ default (no keyword): Visible only within the same package.

For an interface, public is the only access specifier that can be used directly for
the interface itself. Its members are implicitly public.

3.3 The this Keyword: Referring to Self 🤳


11
The “this” keyword is a reference to the current object. It's often used:

●​ To refer to the current class's instance variables when there's a name


collision with method parameters.
●​ To invoke the current class's constructor.

3.4 The super Keyword: Reaching Up to the Parent 👆


The super keyword is used to refer to members of the immediate superclass. It's
used to:

●​ Access a superclass's method that has been overridden by the subclass.


●​ Access a superclass's hidden instance variables.
●​ Call a superclass's constructor from the subclass's constructor. The correct
way to call a constructor of superclass A by subclass B with no parameters is
super();.

3.5 Packages: Organizing Your Code 📦


Packages in Java are a way to organize related classes and interfaces into logical
groups. They help prevent naming conflicts and improve code modularity.
Think of them as folders for your code files.

●​ To access features of a package, you use the import keyword.


●​ To import an entire package pkg, you use import pkg.*;.
●​ Commonly used packages:
○​ java.lang: Fundamental classes (e.g., String, Object, System, Math). It's
implicitly imported.
○​ java.util: Utility classes (e.g., ArrayList, HashMap, Scanner).
○​ java.io: Input/Output operations (e.g., file handling).
○​ java.awt (Abstract Window Toolkit): Classes for creating graphical user
interfaces (GUIs), including windows, buttons, lists, and menus.

12
○​ java.net: Networking classes.

3.6 Identifiers: Naming Your Code Elements 🏷️


An identifier is a name given to a class, variable, method, or package. There are
rules for valid identifiers:

●​ 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).

3.7 Automatic Type Conversion: Smooth Transitions 🔄


Automatic type conversion (or widening conversion) in Java takes place when
two types are compatible, and the size of the destination type is larger than the
source type. This prevents loss of data. For example, an int can be automatically
converted to a long or a double.

int myInt = 10;​


long myLong = myInt; // Automatic conversion (int to long)​
double myDouble = myInt; // Automatic conversion (int to
double)​

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.

4.1 What's an Exception? A Program's "Oops!" Moment 🫢


An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions. When an error occurs within a
method,7 it can create an exception object and hand it off to the runtime system.
This process is called throwing an exception.

4.2 The Exception Hierarchy 🌳


All exceptional type classes in Java are subclasses of the Throwable class. This is
the superclass of all errors and exceptions.

●​ Error: Represents serious problems that applications should not try to


catch (e.g., VirtualMachineError, OutOfMemoryError).
●​ Exception: Represents conditions that a reasonable application might want
to catch. This is the superclass for all exceptions that can be caught using a
catch block.
○​ RuntimeException: A subclass of Exception that represents errors that
occur during program execution (e.g., ArithmeticException,
NullPointerException, IndexOutOfBoundsException). These are
unchecked exceptions, meaning you don't have to catch them, but it's
good practice.

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)​

4.3 Handling Exceptions: try, catch, finally 🛡️


Java provides keywords to manage exceptions:

●​ 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!");​

●​ throws: This keyword is used in a method signature to declare that the


method might throw a certain type of checked exception. This forces the
calling method to either catch or re-declare the exception.

16
Chapter 5: Building User Interfaces: Java GUI 🖥️
Java provides powerful toolkits for building graphical user interfaces (GUIs).

5.1 AWT and Swing: The Building Blocks 🧱


●​ AWT (Abstract Window Toolkit): Java's original GUI toolkit. It uses native
(platform-specific) components, which can lead to inconsistencies in
appearance across different operating systems.
●​ Swing: A more advanced and flexible GUI toolkit built entirely in Java (pure
Java components). This ensures a consistent "look and feel" across all
platforms, often referred to as "lightweight" components.

5.2 Core GUI Components: Windows and Frames 🖼️


●​ Window: A top-level independent window.
●​ Frame ( JFrame in Swing): A specialized Window that has borders, a title
bar, and basic window controls (minimize, maximize, close). It's an area on
the screen that has nice borders and various buttons along the top border.
When you create a JFrame object (e.g., JFrame myFrame = new JFrame();),
you are essentially calling a constructor.

5.3 Event Handling: Making Interfaces Interactive 🖱️


GUI applications are event-driven. This means they respond to user actions
(like clicks, key presses) or system events. The delegation event model is used
by Java.

●​ Event: An object that describes a state change in a source (e.g., a button


being clicked).
●​ Event Source: The component that generates the event (e.g., a button).

17
●​ Event Listener: An object that "listens" for and handles events.

Common Events and Listeners:

●​ ActionEvent: Generated when a button is pressed, a menu item is selected,


or a list item is double-clicked. The ActionListener interface handles these.
●​ KeyEvent: Generated when a key is pressed, released, or typed. The
KeyListener interface is used to register a keyboard event listener (methods
include keyPressed(), keyReleased(), keyTyped()). You can use getKey() or
getKeyChar() to know which key is pressed.
●​ MouseEvent: Generated when a mouse button is pressed, released, clicked,
entered, or exited. The MouseListener interface handles these.
●​ MouseMotionEvent: Generated when the mouse is moved or dragged. The
MouseMotionListener interface is used to register a mouse motion listener
(methods include mouseDragged(), mouseMoved()).
●​ WindowEvent: Generated when a window is opened, closed, closing,
iconified, deiconified, activated, or deactivated. The WindowListener
interface handles these. When the window is closed, a WindowEvent is
generated.
●​ FocusEvent: Generated when a component gains or loses keyboard focus.
●​ TextEvent: Generated when the text of a text component changes.
●​ AdjustmentEvent: Generated by a scrollbar.

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!

6.1 What's a Thread? A Lightweight Process 🧵


A thread is the smallest unit of a program that can be executed independently.
It's a lightweight process that can run alongside other threads within the same
program.

6.2 Creating and Running Threads 🏁


You can create a thread in Java in two main ways:

1.​ Extending the Thread class:​



class MyThread extends Thread {​
public void run() {​
// Code to be executed by the thread​
}​
}​
// To start: new MyThread().start();
2.​ Implementing the Runnable interface: This is generally preferred as it
allows your class to extend another class if needed.​

class MyRunnable implements Runnable {​
public void run() {​
// Code to be executed by the thread​
}​
}​
// To start: new Thread(new MyRunnable()).start();​

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.

6.3 Thread Life Cycle and Control ♻️


Threads go through various states (e.g., new, runnable, blocked, waiting, timed
waiting, terminated).

●​ sleep(): Pauses a thread's execution for a specified duration. It doesn't


release any acquired locks.
●​ wait(): Causes the current thread to wait until another thread invokes the

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.

6.4 Thread Priority: Who Goes First? 🥇


Thread priority in Java is an integer value. The valid range of priority for a
thread is from 1 to 10, where Thread.MIN_PRIORITY is 1 and
Thread.MAX_PRIORITY is 10. Thread.NORM_PRIORITY is 5. Threads with
higher priority are given preference by the scheduler, though the exact behavior

20
can be platform-dependent. Two threads can have the same priority.

6.5 Multitasking and CPU Utilization 📈


By multitasking, CPU idle time is minimized, and we can make maximum use of
it. It allows a single CPU to appear to be executing multiple programs
concurrently by rapidly switching between them.

21
Chapter 7: String Manipulation and Utility Classes ✂️
Strings are fundamental in Java, and the language provides robust ways to work
with them.

7.1 String Class: Immutable Text 📝


●​ String objects are immutable, meaning their value cannot be changed after
creation. If you perform an operation that seems to modify a string (like
concat() or replace()), a new String object is actually created with the
modified content.
●​ Comparing Strings:
○​ equals(): Compares two String objects for their equality based on
content. It returns true if the strings have the same sequence of
characters.
○​ compareTo(): Compares two strings lexicographically (based on their
character values). It returns a negative integer, zero, or a positive integer
as the String object is lexicographically less than, equal to, or greater
than the argument string. For example, "ethics" compared to "Ethics" will
result in a positive number because 'e' (lowercase) has a higher ASCII
value than 'E' (uppercase).

7.2 StringBuffer Class: Mutable Text ✍️


The StringBuffer class is used to store strings in a buffer for later use and allows
for mutable (changeable) strings. If you need to perform many modifications to
a string, StringBuffer (or StringBuilder for single-threaded environments) is
more efficient than repeatedly creating new String objects.

7.3 toString() Method: Object to String Conversion 🔄


22
The toString() method is a Java method used to convert an object to its string
representation. It's often overridden in custom classes to provide a meaningful
string representation of the object's state.

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.

8.1 The File Class: File System Operations 📁


The File class represents a file or directory path. It doesn't actually interact with
the file content but provides methods to check file properties and perform file
system operations.

●​ canWrite(): Checks if the application can write to the file.


●​ canRead(): Checks if the application can read from the file.
●​ getName(): Returns the name of the file or directory denoted by this
abstract pathname.

8.2 Input Streams: Reading Data ➡️


●​ InputStream: The superclass for all input streams.
●​ FileInputStream: Used to read bytes from a file.
●​ BufferedInputStream: A filter input stream that adds buffering functionality
to another input stream, improving reading performance.

8.3 Output Streams: Writing Data ⬅️


●​ OutputStream: The superclass for all output streams.
●​ write(int b): Writes the specified byte to the current output stream.
●​ write(byte[] b): Writes b.length bytes from the specified byte array to this
output stream.
●​ flush(): Flushes the output stream and forces any buffered output bytes to be
written out.
●​ close(): Closes the output stream.

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)

9.2 API Documentation: Javadoc 📚


The javadoc tool is used to generate API (Application Programming Interface)
documentation in HTML format directly from special comments (doc
comments) within your source code. This is incredibly useful for documenting
your code and making it easy for others (and your future self!) to understand.

9.3 System Properties and Environment Variables 🌍


Java applications can access system properties and environment variables.

●​ java.home: Stores the installation directory of the JRE ( Java Runtime


Environment).
●​ user.home: Stores the user's home directory.
●​ user.dir: Stores the current working directory.
●​ java.class.path: Stores the class path.

You can use @Property annotations or System.getProperty() to access these.

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.

// Example: Creating an anonymous inner class that extends Boo​


Boo f = new Boo() {​
// This is the body of the anonymous inner class​
// You can override methods here if Boo has them​
};​

10.2 Operator Precedence and Associativity ➡️⬅️


When operators have the same priority (precedence), they are evaluated based
on their associativity (left-to-right or right-to-left) in the order they appear in
the expression.

10.3 Robustness: Crash Protection! 💪


One of the key features of Java is its robustness. Java programs are designed not
to crash easily because of its strong type checking, exception handling
mechanism, and automatic memory management (garbage collection).

10.4 Generic Classes: Flexible Types 📦


A template class is another term for a generic class. Generic classes allow you
to write code that works with different types without having to rewrite the
entire class for each type. They enable type safety while providing flexibility.

10.5 Member Accessibility to Subclasses 🔒


26
While inheritance allows sharing, not all members are equally accessible:

●​ public members: Always accessible to subclasses.


●​ protected members: Accessible to subclasses.
●​ private members: Never accessible to the subclass directly. Encapsulation
ensures they remain hidden.
●​ default (friendly) members: Accessible within the same package, but not by
subclasses in different packages.

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

You might also like