Page |1
Index
Contents
1. Chapter................................................................................................................................................ 4
Introduction to Java ................................................................................................................................ 4
JAVA ........................................................................................................................................................ 4
Features of Java ...................................................................................................................................... 4
Java’s Magic: The Bytecode ................................................................................................................ 6
What Is Bytecode? .............................................................................................................................. 6
Why Bytecode? ................................................................................................................................... 7
How It Works (In Simple Terms) ......................................................................................................... 7
Extra Benefit: Security......................................................................................................................... 7
Real-Life Analogy................................................................................................................................. 7
Summary ............................................................................................................................................. 7
Object-Oriented Programming (OOPs) with Java ............................................................................... 8
4 Main Pillars of OOP in Java........................................................................................................... 8
Summary ........................................................................................................................................... 11
2. Chapter.............................................................................................................................................. 11
Introduction ...................................................................................................................................... 11
1. Data Types – What Kind of Data? ................................................................................................. 11
Primitive Data Types (built-in) ...................................................................................................... 11
Non-Primitive (Reference) Data Types ......................................................................................... 12
2. Variables – Naming Your Data ...................................................................................................... 12
3. Arrays – Storing Multiple Values................................................................................................... 13
Summary ........................................................................................................................................... 13
Type Conversion in Java .................................................................................................................... 13
1. Implicit Type Conversion (Widening Conversion) ..................................................................... 14
2. Explicit Type Conversion (Narrowing Conversion) .................................................................... 14
Summary Table ................................................................................................................................. 15
3. Chapter.............................................................................................................................................. 16
Access Specifiers in Java .................................................................. 17
1. private — Most Restricted ....................................................... 17
2. Default (no keyword) — Package-Private ................................ 17
Page |2
3. protected — In Package + Inheriting Subclasses ...................................................................... 18
4. public — No Restrictions ........................................................................................................... 18
Summary Table ................................................................................................................................. 18
4. Chapter.............................................................................................................................................. 20
• Operators • Loops .............................................................................................................................. 20
• Funtions(methods) ............................................................................................................................. 20
• Control statements in Java................................................................................................................. 20
Operators in Java .............................................................................................................................. 20
Types of Operators:....................................................................................................................... 20
Loops in Java ..................................................................................................................................... 23
Types of Loops: ............................................................................................................................. 23
Functions (Methods) in Java ............................................................................................................. 24
Control Statements in Java ............................................................................................................... 25
5. Chapter.............................................................................................................................................. 27
Introducing Classes, Abstraction,.......................................................................................................... 27
and Encapsulation, Polymorphism. ...................................................................................................... 27
What is a Class in Java? ..................................................................................................................... 27
What is an Object in Java? ................................................................................................................ 27
Lets See What is Constructor in Detail.............................................................................................. 30
What is a Constructor in Java? ...................................................................................................... 30
Types of Constructors ................................................................................................................... 30
Constructor Overloading............................................................................................................... 32
Constructor vs Method ................................................................................................................. 33
Method Overloading (Compile-time Polymorphism) ................................................................... 33
Method Overriding (Runtime Polymorphism) .............................................................................. 34
Comparison Table ......................................................................................................................... 35
Encapsulation .................................................................................................................................... 35
Abstraction ........................................................................................................................................ 36
6. Chapter.............................................................................................................................................. 37
Important Terms to Understand. .......................................................................................................... 37
Inheritance, Static, final, Object Class.................................................................................................. 37
What is Inheritance? ......................................................................................................................... 37
Types of Inheritance in Java .......................................................................................................... 37
Why Multiple Inheritance is Not Supported via Classes? ............................................................. 39
Inheritance with Constructors .......................................................................................................... 39
Method Overriding in Inheritance .................................................................................................... 40
Page |3
super Keyword .................................................................................................................................. 40
Access Modifiers in Inheritance ........................................................................................................ 40
Final Keyword and Inheritance ......................................................................................................... 41
Abstract Classes and Inheritance ...................................................................................................... 41
Interface Inheritance (Multiple Inheritance) .................................................................................... 41
Key Benefits of Inheritance ............................................................................................................... 42
static-Keyword in Java ...................................................................................................................... 42
1. Static Variables (a.k.a. Class Variables) ..................................................................................... 43
2. Static Methods .......................................................................................................................... 43
3. Static Blocks .............................................................................................................................. 43
4. Static Class (Nested) .................................................................................................................. 44
5. Static Import.............................................................................................................................. 44
Static vs Non-Static Comparison ....................................................................................................... 45
final Keyword in Java ........................................................................................................................ 45
1. final Variable ............................................................................................................................. 45
2. final Method.............................................................................................................................. 46
3. final Class................................................................................................................................... 47
Final Keyword in Real World Use-Cases........................................................................................ 47
Object Class in Java ........................................................................................................................... 48
Why is Object Class Important? .................................................................................................... 48
Key Methods of Object Class ........................................................................................................ 48
Summary Table ................................................................................................................................. 51
Page |4
1. Chapter
Introduction to Java
JAVA
Java is a powerful, high-level programming language that was developed by Sun
Microsystems in 1995 and is now maintained by Oracle Corporation. Known for its versatility,
security, and performance, Java has become one of the most widely used programming
languages in the world.
Its syntax is similar to C++, but Java was designed to be simpler and more robust. It removes
many of the complex features found in C++, such as manual memory management and the
use of pointers. One of Java’s biggest strengths is its platform independence—thanks to the
Java Virtual Machine (JVM), Java code can be written once and run anywhere, regardless of
the underlying operating system. This principle is often summed up by the phrase: "Write
Once, Run Anywhere" (WORA).
Features of Java
Java is packed with powerful features that make it one of the most popular and reliable
programming languages in the world. Here’s a breakdown of its key features:
1. Simple
Page |5
Java is designed to be easy to learn and use. It has a clean, readable syntax and removes
complex features like pointers and operator overloading, making it more beginner-friendly.
2. Object-Oriented
Everything in Java revolves around objects and classes. This approach promotes code
reusability, scalability, and easier maintenance.
Core concepts include:
• Class & Object
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
3. Platform-Independent
Java code is compiled into bytecode, which can run on any system with a Java Virtual
Machine (JVM). This makes Java truly cross-platform.
"Write Once, Run Anywhere" – a core Java principle.
4. Secure
Java provides a secure environment for developing applications. It avoids explicit pointer
usage and has features like:
• Bytecode verification
• Security APIs
• Runtime security checks
5. Robust
Java emphasizes early error checking and has strong memory management, including:
• Exception handling
• Garbage collection
Page |6
• Type safety
This helps prevent crashes and memory leaks.
6. Multithreaded
Java supports multithreading, allowing multiple tasks to run simultaneously. This is great for
building responsive and high-performance applications like games or servers.
7. High Performance
Java code is compiled to efficient bytecode and uses Just-In-Time (JIT) compilation at
runtime, making it faster than purely interpreted languages.
8. Distributed
Java supports networking and distributed computing out of the box. APIs like [Link] and
features like RMI (Remote Method Invocation) allow Java programs to easily interact across
networks.
9. Dynamic and Extensible
Java can dynamically load classes at runtime. It supports reflection and flexible linking,
making applications adaptable and scalable.
Java’s Magic: The Bytecode
One of the things that makes Java so powerful and unique is something called bytecode. It’s
not something you normally see, but it plays a huge role in how your Java program runs.
What Is Bytecode?
When you write a Java program, you write it in a file ending with .java — that's your source
code. But computers don’t understand Java directly. So when you compile your code (using
javac), Java translates it into something called bytecode, which is stored in a .class file.
Bytecode is like a middle language — it’s not as readable as Java, but it’s not as low-level as
machine code either.
Page |7
Why Bytecode?
Here's where the magic happens:
Instead of compiling your code directly into machine language (which would only work on
one type of computer), Java turns it into bytecode, which can run anywhere that has a Java
Virtual Machine (JVM).
Write Once, Run Anywhere — because bytecode can be run on any device with a JVM.
How It Works (In Simple Terms)
1. You write Java code → [Link]
2. You compile it → javac [Link]
3. It becomes bytecode → [Link]
4. The JVM reads the bytecode and translates it on the fly into native code that your
machine understands.
5. The program runs
Extra Benefit: Security
Since the JVM checks the bytecode before running it, Java can catch a lot of errors or
dangerous behavior before it ever reaches your computer’s hardware. This makes Java
programs more secure than many others.
Real-Life Analogy
Think of Java source code like writing instructions in English.
Bytecode is like a universal translation — not English, not French, not Spanish, but
something all translators (JVMs) understand and can turn into the right local language for
any audience.
Summary
• Bytecode is what makes Java cross-platform.
Page |8
• It acts as a bridge between your code and the machine.
• JVM takes care of converting bytecode to machine code.
• This process makes Java flexible, secure, and portable.
Object-Oriented Programming (OOPs) with Java
Object-Oriented Programming (OOP) is a programming paradigm that organizes software
design around objects, rather than functions and logic. Java is a fully object-oriented
language, which means almost everything in Java revolves around objects and classes.
Why Use OOP?
• Makes code reusable, modular, and easier to maintain
• Models real-world concepts using objects
• Supports better data security and code organization
4 Main Pillars of OOP in Java
1. Encapsulation
Definition: Binding data (variables) and methods (functions) into a single unit — a class —
and restricting direct access to some of the object's components.
Example:
Benefits: Data hiding, controlled access, security
Page |9
2. Inheritance
Definition: One class (child/subclass) inherits the properties and methods of another class
(parent/superclass).
Example:
Benefits: Code reusability, hierarchical classification
➔ Don't Worry about “[Link](myDouble);” We will discuss it in detail in
upcoming lessons. For now, just remember it is used to print the value between the
parenthesis (“xyz”).
3. Polymorphism
Definition: The ability of a single function or method to behave differently based on the
object or context.
Types:
• Compile-time (Method Overloading):
• Runtime (Method Overriding):
P a g e | 10
Benefits: Flexibility and scalability
4. Abstraction
Definition: Hiding complex implementation details and showing only the essential features.
Achieved using:
• Abstract classes
• Interfaces
Example using interface:
Benefits: Focus on what an object does instead of how
Additional OOP Concepts in Java
• Class & Object: Blueprints vs real-world instances
• Constructor: Special method used to initialize objects
• ‘this’ Keyword: Refers to the current object instance
P a g e | 11
• Access Modifiers: Control visibility (public, private, protected)
Summary
Java’s OOP principles help you build clean, reusable, and scalable code. By mastering
encapsulation, inheritance, polymorphism, and abstraction, you can write Java applications
that are more efficient, organized, and easier to maintain.
2. Chapter
Data Types, Variables, and
Arrays in Java
Introduction
When you write a program in Java, you're working with data — numbers, text, true/false
values, and more. To manage that data, Java uses data types, variables, and arrays. Let’s
break these down in simple terms.
1. Data Types – What Kind of Data?
Data types in Java define what kind of value a variable can hold. Java is a strongly typed
language, which means every variable must have a specific type.
Two main categories:
Primitive Data Types (built-in)
Type Example Value Description
int 25 Whole numbers
P a g e | 12
float 5.75f Decimal numbers (with f)
Larger or more precise
double 3.14159
decimals
char 'A' Single characters
boolean true / false True or false values
byte 127 Small numbers (-128 to 127)
short 32000 Medium whole numbers
long 123456789L Big whole numbers (with L)
Non-Primitive (Reference) Data Types
• Used for objects like:
o String – for text
o Arrays
o Custom classes and interfaces
2. Variables – Naming Your Data
A variable is like a labelled box where you store data.
How to declare a variable:
Here’s what’s happening:
• int is the data type
• age is the variable name
• 25 is the value assigned
You can change the value later, but the type stays the same.
P a g e | 13
3. Arrays – Storing Multiple Values
An array is like a row of boxes where you can store multiple values of the same type.
Declaring and using an array:
• int[] → an array of integers
• numbers[2] → accesses the third element (Java starts counting from 0!)
You can also create an empty array and add values later:
Summary
Concept Think of It As... Purpose
Data Type The kind of value (number, text, etc.) Tells Java what to expect
Variable A labelled container Stores one value
Array A shelf of containers Stores multiple values
Type Conversion in Java
Type conversion in Java means changing one data type into another. This is often needed
when you’re combining different kinds of data, doing calculations, or working with method
parameters.
Java provides two main types of type conversion:
P a g e | 14
1. Implicit Type Conversion (Widening Conversion)
Also known as automatic type conversion, this happens when Java automatically converts a
smaller data type into a larger one without any extra code.
Why it works:
• There’s no data loss.
• It’s safe and Java handles it internally.
Example:
Widening conversion order:
This means a byte can go into a short, a short into an int, and so on, automatically.
2. Explicit Type Conversion (Narrowing Conversion)
Also called type casting, this happens when you manually convert a larger data type into a
smaller one. Since this can lead to data loss, Java requires you to do it explicitly.
Example:
Warning:
• You may lose precision or data.
• Always use narrowing with caution.
Examples of Both Conversions
Implicit (Widening):
P a g e | 15
Explicit (Narrowing):
Why Use Type Conversion?
• To perform operations between different types
• When passing arguments to methods that expect a different type
• To store a value into a variable of another type
• For compatibility with legacy APIs
Good Practices
• Use implicit conversion whenever possible (it's safe).
• Use explicit conversion only when you're sure it won’t break your logic or cause data
loss.
• Always test the result of narrowing conversions.
Summary Table
Type Automatic? Safe? Example
Implicit (Widening) Yes Yes int → long, float → double
Explicit (Narrowing) No Risky double → int, long → byte
P a g e | 16
Fun Fact
Java was originally designed for interactive television!
In the early 1990s, James Gosling and his team at Sun Microsystems created Java for a
project called Green, intended to develop software for interactive TVs. But the technology
was too advanced for the digital cable industry at the time. Later, they realized Java’s
potential for internet applications, especially as the web was starting to grow—leading to
Java's massive success as a cross-platform language with the slogan: "Write Once, Run
Anywhere."
3. Chapter
Access Specifiers in Java
P a g e | 17
Access Specifiers in Java
Access specifiers (also called access modifiers) in Java are keywords that control who can
access classes, methods, variables, and constructors. They help enforce encapsulation and
security in your code.
Think of them like privacy settings for your code — you decide what should be public,
private, or hidden from others.
Java Provides 4 Main Access Specifiers:
Access Accessible Accessible Accessible by Subclass Accessible
Specifier Within Class Within Package (Other Package) Everywhere
private Yes No No No
(default) (no
keyword) Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
1. private — Most Restricted
• Can only be accessed within the same class.
• Not visible to other classes, even in the same package.
Use when you want to hide internal details completely.
2. Default (no keyword) — Package-Private
• If you don’t write any access specifier, it’s default.
• Accessible only within the same package.
P a g e | 18
Use when you want access only within the same package.
3. protected — In Package + Inheriting Subclasses
• Accessible in the same package.
• Also accessible in subclasses from other packages via inheritance.
Use when you want to allow subclass access across packages.
4. public — No Restrictions
• Accessible from anywhere.
• Can be used across classes, packages, and even projects.
Use when you want code to be completely open and reusable.
Summary Table
Keyword Scope Keyword Example
private Only inside the declared class private int age;
default Same package only (no keyword) void show();
protected Same package + subclasses in other packages protected void draw();
public Accessible from anywhere public String name;
P a g e | 19
Fun Fact
The name “Java” comes from coffee!
Before it was called Java, the language was originally named Oak, after an oak tree that
stood outside James Gosling’s office. But that name was already taken by another language.
The team then brainstormed and chose "Java", inspired by the coffee from the Indonesian
island of Java. That’s why the Java logo is a steaming cup of coffee!
So yes—Java is literally named after coffee!
In the next chapters we are going to learn about some general programming features and
concepts that is mandatory for all programming languages
For Example:
• Operators
• Loops
• Funtions(methods)
• Control statements
• Etc.
P a g e | 20
4. Chapter
• Operators • Loops
• Funtions(methods)
• Control statements in Java
Operators in Java
Operators are special symbols used to perform operations on variables and values.
Types of Operators:
1. Arithmetic Operators : +, -, *, /, %
2. Relational (Comparison) Operators: : ==, !=, >, <, >=, <=
3. Logical Operators: : &&, ||, !
4. Assignment Operators: : =, +=, -=, etc.
5. Unary Operators: : ++, --, +, -
6. Bitwise Operators: : &, |, ^, ~, <<, >>
Example:
P a g e | 21
Let's break down every important concept used in this Java program.
1. Class Declaration
• public: An access modifier – makes the class accessible from anywhere.
• class: Used to define a class – a blueprint for objects in Java.
• OperatorExample: The name of the class (must match the filename
[Link]).
2. Main Method
• This is the starting point of every Java program.
• public: Makes this method accessible from anywhere.
• static: Means it belongs to the class and doesn't require creating an object.
• void: This method does not return any value.
• main: The method name – JVM looks for this to start running the program.
• String[] args: Command-line arguments (can be empty or passed during execution).
P a g e | 22
3. Arithmetic Operator
• a + b: Adds 10 + 20 = 30.
• +: In this case, it performs addition and also string concatenation.
• "a + b = " + (a + b): Combines text with the result, using parentheses to calculate
before printing.
4. Relational (Comparison) Operator
• ==: Checks if two values are equal.
• Since 10 == 20 is false, the output will be: a == b: false.
5. Logical Operator
• &&: Logical AND – both conditions must be true:
❖ a < b → 10 < 20 → true
❖ a > 5 → 10 > 5 → true
• So the whole expression is true && true → true
• Output: a < b && a > 5: true
6. Assignment Operator
• +=: A shorthand assignment operator.
• a += 5 means: take current a (10), add 5, and store back in a.
• So a becomes 15.
P a g e | 23
• Output: a after += 5: 15
Summary of Concepts Covered:
Concept What It Does
int a = 10 Declares and initializes variables
+ Arithmetic addition
== Checks equality
&& Logical AND
+= Adds and assigns value in one step
[Link]() Prints output to the console
main() Entry point of the program
public static void Defines the nature of the main method
Loops in Java
Loops are used to execute a block of code multiple times.
Types of Loops:
1. for loop – Repeats for a known number of times
2. while loop – Repeats while a condition is true
3. do-while loop – Executes at least once, then checks condition
Example:
P a g e | 24
Functions (Methods) in Java
A method is a block of code that performs a specific task. It helps in reusing code.
Syntax:
Example:
P a g e | 25
Control Statements in Java
Control statements change the flow of execution.
Types:
1. if, if-else, else-if – Conditional branching
2. switch – Multiple condition checking
3. break – Exit from loop or switch
4. continue – Skip current iteration
5. return – Exit from a method
Example:
P a g e | 26
P a g e | 27
5. Chapter
Introducing Classes, Abstraction,
and Encapsulation, Polymorphism.
In object-oriented programming (OOP), the concept of a "class" lies at the heart of software
development. Java, being a strongly object-oriented language, treats everything as an
object, and every object is an instance of a class. This chapter introduces the foundational
concept of classes in Java, helping you understand how Java structures and organizes code in
an object-oriented manner.
We begin by exploring what a class is — a blueprint or template for creating objects — and
how it encapsulates data (fields) and behaviour (methods). You'll learn about class syntax,
constructors, fields, methods, and how objects are created and used in Java programs. The
chapter also covers key object-oriented principles such as encapsulation and abstraction as
they relate to classes.
By the end of this chapter, you will be equipped with the knowledge to define your own
classes, instantiate objects, and use them effectively in Java applications. This understanding
sets the stage for more advanced topics such as inheritance, polymorphism, and interfaces,
which will be discussed in later chapters.
What is a Class in Java?
A class in Java is a blueprint or template for creating objects. It defines:
• The state (attributes or fields)
• The behaviour (methods or functions)
Think of a class like a car design: it defines what a car should have (wheels, engine) and what
it can do (start, stop), but it's not a real car until it's built. That real, built car is the object.
What is an Object in Java?
An object is an instance of a class. It is created from the class blueprint and represents a
real-world entity.
For example:
• Class: Map of the House
P a g e | 28
• Object: The real house that we Create from the Map
Class(Map) Real House(Object)
• Programming Example
• Output
P a g e | 29
Let’s go through each and every line of above code.
1. Class Definition
• A class is a blueprint or template.
• Here we are defining a class named Student.
2. Attributes (Fields)
• These are instance variables (also called fields or attributes).
• Each object of the Student class will have a name, age, and grade.
3. Constructor
• A constructor is a special method that runs automatically when an object is created.
• [Link] = name; means:
o The left name refers to the object's attribute.
o The right name is the parameter passed during object creation.
4. Method
• This is a method called displayInfo.
P a g e | 30
• It prints the values of the student's attributes.
• You call this method using an object (like [Link]()).
5. Main Method and Object Creation
• public static void main(String[] args) is the entry point of every Java program.
• Student student1 = new Student(...) creates an object of the Student class.
• [Link](); calls the method to print that student's info.
Lets See What is Constructor in Detail
What is a Constructor in Java?
A constructor is a special method used to initialize objects when they are created.
Key Points:
• A constructor has the same name as the class.
• It does not have a return type (not even void).
• It is automatically called when you create an object using new.
Types of Constructors
1. Default Constructor
2. Parameterized Constructor
3. No-Arg Constructor (if created explicitly)
1. Default Constructor (Provided by Java)
If you don’t write any constructor, Java automatically creates a default constructor with no
parameters.
P a g e | 31
2. No-Argument Constructor (Written by You)
3. Parameterized Constructor (Most Common)
P a g e | 32
Example with Explanation
Output
Constructor Overloading
P a g e | 33
Constructor vs Method
Feature Constructor Method
Name Same as class Any name
Return type No return type, not even void Must have return type
Called by Automatically on object creation Manually by object
Purpose Initializes object Defines object behaviour
Method Overloading (Compile-time Polymorphism)
Definition:
Method overloading occurs when multiple methods in the same class have the same name
but different parameters (type, number, or both). It is resolved at compile time.
Key Points:
• Same method name.
• Different parameter list.
• Can have different return types (but not only return type).
• Happens in the same class.
Example:
P a g e | 34
Method Overriding (Runtime Polymorphism)
Definition:
Method overriding occurs when a subclass provides its own implementation of a method
that is already defined in its superclass. It is resolved at runtime.
Key Points:
• Same method name, same parameters.
• Happens in inheritance (between superclass and subclass).
• The subclass overrides the superclass’s method.
• Must have the same return type (or covariant).
• Use @Override annotation for better readability and error checking.
• The method in superclass must be non-static and non-private.
Example:
Even though the reference is of type Animal, the actual method executed is from Dog
because of runtime polymorphism.
P a g e | 35
Comparison Table
Feature Method Overloading Method Overriding
Same method name, different
Definition Same method signature in subclass
parameters
Class Involved Same class Inheritance (subclass + superclass)
Can differ (but not only return
Return Type Must be same or covariant
type)
Parameters Must be different Must be same
Polymorphism
Compile-time Runtime
Type
Cannot override private, must be at
Access Modifier Irrelevant
least as visible
Encapsulation
Encapsulation is binding data (variables) and methods (functions) that operate on the data
into a single unit, typically a class. It hides the internal state of the object from outside
access, exposing only what is necessary via public methods.
Key Points:
• Achieved using private fields and public getter/setter methods.
• Protects data from unwanted modification.
• Makes code more maintainable and secure.
P a g e | 36
• The internal fields name and age cannot be accessed directly.
• Instead, they are accessed and modified through methods like setName() and
getAge().
Abstraction
Abstraction means hiding complex implementation details and showing only the essential
features of the object. It helps in reducing complexity and increasing efficiency.
Key Points:
• Achieved using abstract classes and interfaces.
• Focuses on what an object does, not how it does it.
Example with Abstract Class:
• makeSound() is abstract — it doesn't define how it works.
• The subclass Dog provides the specific implementation.
Summary Table
Feature Encapsulation Abstraction
Protect data by hiding internal Hide complexity by exposing essential
Purpose
state features
Use private fields and public
How Use abstract classes and interfaces
methods
Focus How data is accessed/modified What an object does
Example
Getters and Setters Abstract classes / Interfaces
Tool
P a g e | 37
6. Chapter
Important Terms to Understand.
Inheritance, Static, final,
Object Class.
What is Inheritance?
Inheritance is one of the core concepts of Object-Oriented Programming (OOP). It allows
one class (called the child or subclass) to inherit fields and methods from another class
(called the parent or superclass).
This promotes code reusability, extensibility, and modularity.
Syntax of Inheritance
extends keyword is used for inheritance.
Types of Inheritance in Java
Java supports the following types of inheritance:
Type Supported in Java? Example
Single Inheritance Yes One class inherits from another
Multilevel Inheritance Yes A class inherits from a class, which inherits from another
Hierarchical Inheritance Yes Multiple classes inherit from one superclass
Multiple Inheritance (via classes) No Not allowed with classes (but can use interfaces)
P a g e | 38
Hybrid Inheritance Partially Achieved using interfaces
Example of Single Inheritance
Multilevel Inheritance
P a g e | 39
Hierarchical Inheritance
Why Multiple Inheritance is Not Supported via Classes?
• Multiple inheritance (like class C extends A, B) causes ambiguity (diamond problem).
Java avoids it by not supporting multiple inheritance using classes, but it allows it
through interfaces.
Inheritance with Constructors
• Constructors are not inherited, but the child constructor always calls the parent
constructor (explicitly using super() or implicitly).
P a g e | 40
Method Overriding in Inheritance
Child class can override a method of the parent class:
super Keyword
Used to:
1. Call parent class constructor.
2. Access parent class method/field that is overridden.
Access Modifiers in Inheritance
Modifier Accessible in subclass? In same package In other package
private No No No
default (no modifier) if in same package Yes No
protected Yes (inherited) Yes Yes (via subclass)
public Yes Yes Yes
P a g e | 41
Final Keyword and Inheritance
• final class cannot be extended.
• final method cannot be overridden.
Abstract Classes and Inheritance
An abstract class cannot be instantiated but can be extended.
Interface Inheritance (Multiple Inheritance)
Java allows a class to implement multiple interfaces.
P a g e | 42
Key Benefits of Inheritance
1. Code Reusability
2. Polymorphism Support
3. Extensibility
4. Maintenance Ease
static-Keyword in Java
What is static in Java?
The static keyword in Java is used to indicate that a member (variable, method, block, or
nested class) belongs to the class rather than to any specific instance (object) of the class.
So, you can access it without creating an object.
Where can static be used?
Element Static Allowed? Purpose
Variable Yes Shared across all objects
Method Yes Can be called without object
Block Yes Static initializer block
Nested Class Yes Static inner class
Constructor No Constructors cannot be static
P a g e | 43
1. Static Variables (a.k.a. Class Variables)
Shared among all instances of the class.
If you change college, it affects all instances.
2. Static Methods
Can be called without creating an object. They cannot access non-static members
directly.
Rules:
• Can access only static data.
• Cannot use this or super.
• Can be called via class name.
3. Static Blocks
Static initializer blocks are used for static initialization (e.g., loading drivers, setting up
resources).
P a g e | 44
Output:
Executed only once when class is loaded.
4. Static Class (Nested)
You can define a static nested class inside another class.
• Can access static members of the outer class.
• Does not need an instance of outer class.
5. Static Import
You can use import static to access static members without class name prefix.
P a g e | 45
Static vs Non-Static Comparison
Feature Static Non-Static
Belongs to Class Object
Memory Single copy shared New for each object
Access Class name Object
Access non-static? No Yes
Use Cases of static
• Constants (e.g., static final int MAX = 100;)
• Utility methods (e.g., [Link]())
• Counting object instances
• Shared configuration (e.g., database URL)
• Singleton pattern
final Keyword in Java
In Java, the final keyword is a non-access modifier that is used to restrict changes. You can
apply final to:
Element Purpose
Variable Value cannot be changed once assigned
Method Cannot be overridden in subclasses
Class Cannot be inherited (i.e., subclassed)
1. final Variable
A variable declared as final cannot be reassigned after its initial assignment.
Syntax:
P a g e | 46
Types of final variables:
• Local final variable – declared inside a method.
• Instance final variable – declared inside a class but outside any method.
• Static final variable – constant that belongs to the class.
Example:
Once assigned, the value of a final variable cannot be changed.
Final with Objects:
• A final object reference cannot point to another object.
• But the contents of the object can be changed (unless they’re also final).
2. final Method
A method declared final cannot be overridden by subclasses.
Example:
This is used to prevent modification of a method’s behaviour in subclasses.
P a g e | 47
3. final Class
A class declared final cannot be extended (no subclass can inherit from it).
Example:
Used when we want to prevent inheritance completely (e.g., [Link] is a final class).
Final and Constructors
• Final instance variables must be initialized either:
o At declaration
o Inside constructor
Final vs Static vs Constant
Modifier Meaning Example
final Cannot be changed after initialization final int x = 5;
static Belongs to class, not object static int count = 0;
static final Constant, shared & immutable static final int MAX = 100;
Final Keyword in Real World Use-Cases
1. Defining constants:
P a g e | 48
2. Immutable classes (like String)
o Fields are final
o No setters
o Final class to prevent subclassing
3. Secure method behaviour
o Prevent overriding of security-critical methods.
Object Class in Java
What is Object Class?
In Java, the Object class is the root (superclass) of all classes. Every class in Java implicitly
inherits from the Object class, either directly or indirectly.
It is defined in [Link] package and provides common methods that are available to every
object in Java.
Why is Object Class Important?
• Enables polymorphism and type generalization
• Provides basic functionalities for all Java objects
• Forms the base of the Java inheritance tree
Key Methods of Object Class
Method Signature Description
protected Object clone() Creates and returns a copy (shallow clone)
boolean equals(Object obj) Compares two objects for equality
String toString() Returns string representation of the object
int hashCode() Returns hash code of the object
final void wait() / wait(long) / wait(long, int) Used for thread synchronization
final void notify() / notifyAll() Wakes up waiting threads
Class<?> getClass() Returns runtime class of the object
finalize() Called before object is garbage collected (deprecated)
P a g e | 49
1. toString() Method
Returns a string representation of the object.
Default Behaviour:
Custom Example:
2. equals(Object obj) Method
Checks if two references point to the same object (default behavior).
Override Example:
3. hashCode() Method
Returns an integer hash code used in hashing-based collections (like HashMap).
P a g e | 50
Contract:
If two objects are equal via equals(), then they must have the same hashCode().
4. getClass() Method
Returns a Class object representing the runtime class of the object.
5. clone() Method
Used to create a shallow copy of the object. The class must:
• Implement Cloneable interface
• Override clone() method
• Handle CloneNotSupportedException
6. finalize() Method (Deprecated since Java 9)
Called by Garbage Collector before destroying the object. Used to release resources.
P a g e | 51
Deprecated because it creates performance and reliability issues.
7. Thread Methods from Object
These methods are used in synchronized multi-threading.
Method Description
wait() Causes the current thread to wait until another thread calls notify()
notify() Wakes up a single thread waiting on the object's monitor
notifyAll() Wakes up all threads waiting on the object's monitor
Used inside synchronized blocks or methods.
Real-World Example: Polymorphism with Object
Summary Table
Method Purpose Overridable
toString() String representation Yes
equals() Check equality Yes
hashCode() Hash value Yes
clone() Copy of object Yes
getClass() Runtime class info No
wait()/notify() Thread sync No
finalize() Cleanup before GC (deprecated) Yes
P a g e | 52
PART-2 COMING SOON