OOP Using Java — 24CSK42
Module 1 & 2 — Comprehensive Study Notes
Includes: Notes | Syntax | Code Examples | Question Bank Answers
MODULE 1: Introduction to Java
1.1 Java Programming Language — History
• Originally called OAK; designed for portable devices and set-top boxes — it failed.
• In 1995, Sun renamed it Java and pivoted to the World Wide Web.
• In 2009, Oracle Corporation acquired Sun Microsystems and now owns Java, MySQL, and Solaris.
1.2 Components — JDK, JVM, JRE
JDK (Java Development Kit)
A software development environment for writing and running Java programs.
• Contains tools: compiler (javac), applet viewer, Java launcher.
• The compiler converts Java source code into bytecode.
• Can have multiple JDK versions installed on the same machine.
JVM (Java Virtual Machine)
An engine that provides a runtime environment; converts bytecode into machine language.
• Makes Java platform-independent: write once, run anywhere.
• Contains JIT (Just-in-Time) compiler — converts bytecode to native machine code at runtime for speed.
• JVM is part of JRE.
JRE (Java Runtime Environment)
Provides libraries and JVM needed to run a Java program (but not to develop one).
• Contains: class libraries, loader class, JVM.
• Includes packages: math, swing, util, lang, awt, runtime.
• Required to run Java applets.
📌 Note: JDK ⊃ JRE ⊃ JVM. Hierarchy: JDK contains JRE which contains JVM.
Java Platforms
Platform Purpose
Java SE Core functionality, data types, networking, GUI (AWT/Swing), XML parsing
Java EE Enterprise — scalable, multi-tiered, secure network applications
Java ME Mobile/embedded devices — small-footprint VM
JavaFX Rich internet applications — hardware-accelerated graphics
1.3 Java Buzzwords (Features)
The primary objective: make Java portable, simple, and secure.
Buzzword Meaning
Simple Easy to learn, syntax similar to C/C++ but without complex features like pointers
Object-Oriented Based on objects and classes; supports encapsulation, inheritance, polymorphism
Portable Programs run on any platform without modification
Platform Independent Bytecode runs on any OS with a JVM — 'Write Once, Run Anywhere'
Secured No explicit pointers; bytecode verified before execution
Robust Strong memory management, exception handling, type checking
Architecture Neutral Bytecode not tied to specific processor architecture
Interpreted Bytecode is interpreted by JVM at runtime
High Performance JIT compiler improves execution speed
Multithreaded Supports concurrent execution of multiple threads
Distributed Designed for distributed computing environments (RMI, EJB)
Dynamic Supports dynamic loading of classes at runtime
1.4 Java Variables
A variable is a named memory location that holds a value during program execution.
Type Where Declared Key Property
Local Inside a method/block Scope limited to that method; cannot be static
Instance Inside class, outside Each object gets its own copy; not shared
methods
Static Inside class with static Single copy shared by all instances; memory allocated once at
keyword class load
Example — All Three Variable Types:
class A {
int data = 50; // instance variable
static int m = 100; // static variable
void method() {
int n = 90; // local variable
}
}
Type Conversion
• Widening (automatic): int → float (no data loss)
int a = 10; float f = a; // f = 10.0 (auto widening)
• Narrowing (explicit cast required): float → int
float f = 10.5f; int a = (int)f; // a = 10 (truncates)
• Overflow: When cast exceeds target range (e.g., 130 → byte = -126)
1.5 Primitive Data Types
Java is statically-typed — all variables must be declared before use. Java uses Unicode (not ASCII), hence char
is 2 bytes.
Type Size Range Use / Notes
boolean 1 bit* true / false Flags/conditions (*size not precisely defined)
byte 8-bit -128 to 127 Memory-efficient; 4× smaller than int
short 16-bit -32,768 to 32,767 2× smaller than int
int 32-bit -2^31 to 2^31-1 Default integer type
long 64-bit -2^63 to 2^63-1 Use suffix L: 100000L
float 32-bit IEEE754 Unlimited Use suffix f: 3.14f; not for currency
double 64-bit IEEE754 Unlimited Default decimal type; not for currency
char 16-bit Unicode '\u0000' to '\uffff' Stores characters; 2 bytes due to Unicode
📌 Note: Non-primitive types include Classes, Interfaces, and Arrays.
1.6 Arrays
A fixed-size sequential collection of elements of the same type. Array indices start from 0.
Declaration and Creation:
// Declaration (preferred)
double[] myList;
// Creation
myList = new double[10];
// Combined declaration + creation
double[] myList = new double[10];
// With initialization
double[] myList = {1.9, 2.9, 3.4, 3.5};
Processing Arrays:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all elements
for (int i = 0; i < [Link]; i++)
[Link](myList[i]);
// Sum
double total = 0;
for (int i = 0; i < [Link]; i++) total += myList[i];
[Link]("Total: " + total); // 11.7
}
}
1.7 Operators in Java
Operator Type Symbols Description
Arithmetic + - * / % Basic math; % returns remainder
Assignment = += -= *= /= %= num2 += num1 means num2 = num2 + num1
Auto inc/dec ++ -- num++ = num+1; num-- = num-1
Logical && || ! &&: both true; ||: at least one true; !: NOT
Relational == != > < >= <= Comparison operators returning boolean
Bitwise & | ^ ~ << >> Operate bit-by-bit on integer values
Ternary condition ? val1 : val2 Returns val1 if true, val2 if false
Bitwise Quick Reference (num1=11=00001011, num2=22=00010110):
• num1 & num2 → 2 (bits match where both are 1)
• num1 | num2 → 31 (bits where at least one is 1)
• num1 ^ num2 → 29 (bits where they differ)
• ~num1 → -12 (flip all bits)
• num1 << 2 → 44 (shift left 2, multiply by 4)
• num1 >> 2 → 2 (shift right 2, divide by 4)
1.8 Control Statements
Decision Making (if / if-else / nested-if / if-else-if / switch)
// if
if (condition) { // execute if true }
// if-else
if (condition) { // true block } else { // false block }
// if-else-if ladder
if (i==10) println("10");
else if (i==15) println("15");
else if (i==20) println("20");
else println("none");
// switch-case
switch (expression) {
case value1: statement1; break;
case value2: statement2; break;
default: defaultStatement;
}
📌 Note: switch expression can be byte, short, int, char, String (from JDK 7), or enum. Duplicate case values
not allowed.
Jump Statements: break, continue, return
• break: exits loop immediately; can also break to a labeled block (goto substitute)
• continue: skips remaining loop body for current iteration, continues next iteration
• return: exits from a method and optionally returns a value
// break example
for (int i=0; i<10; i++) {
if (i==5) break; // stops at i=4
[Link](i);
}
// continue example
for (int i=0; i<10; i++) {
if (i%2==0) continue; // skips even numbers
[Link](i+" "); // prints: 1 3 5 7 9
}
1.9 Loops
Loop Syntax Key Property
while while (condition) { ... } Entry-controlled; condition checked first
for for (init; condition; update) { ... } Entry-controlled; compact syntax
do-while do { ... } while (condition); Exit-controlled; executes at least ONCE
enhanced for for (T element : collection) { ... } Read-only iteration; no index access
// while
int x = 1;
while (x <= 4) { [Link](x); x++; }
// for
for (int x = 2; x <= 4; x++) [Link](x);
// do-while (runs even if condition is false from start)
int x = 21;
do { [Link](x); x++; } while (x < 20); // prints 21
// enhanced for
String[] arr = {"Ron", "Harry", "Hermione"};
for (String s : arr) [Link](s);
1.10 Command Line Arguments
Information passed to the program at runtime, stored as a String[] in main().
• No restriction on number of arguments.
• All passed as Strings (parsed if other types needed).
• Accessed via args[0], args[1], ..., args[n-1].
• [Link] gives total count.
class CommandLineExample {
public static void main(String[] args) {
[Link]("Count: " + [Link]);
for (int i = 0; i < [Link]; i++)
[Link]("Arg " + i + ": " + args[i]);
}
}
// Run: java CommandLineExample Hello 123 Java
// Output: Count: 3 | Arg 0: Hello | Arg 1: 123 | Arg 2: Java
1.11 Object-Oriented Programming (OOP) Concepts
OOP binds data and functions together so no outside code can access the data without going through the defined
methods.
OOP Pillar Description
Class Blueprint/prototype defining variables and methods. No memory allocated until object is
created.
Object Instance of a class with State (attributes), Behavior (methods), Identity (unique name).
Encapsulation Wrapping data and methods together; variables declared private, accessed via public
getters/setters. Also called data-hiding.
Abstraction Show only essential details; hide irrelevant internals. Achieved via abstract classes and
interfaces.
Inheritance Child class inherits properties/methods of parent class. Enables reusability. Uses
extends keyword.
Polymorphism Same name, different behavior. Two types: Overloading (compile-time) and Overriding
(runtime).
Message Objects communicate by invoking methods on each other (specify object, method, and
Passing data).
Defining a Class and Creating Objects:
class ClassName {
// variables (fields)
// methods
}
// Create objects using new
ClassName obj = new ClassName();
// Access members using dot operator
[Link]();
[Link] = value;
Access Specifiers:
Modifier Accessibility
public Accessible from any class anywhere
protected Accessible within same package AND in subclasses (even outside package)
default (none) Accessible within the same class and same package only
private Accessible ONLY within the same class
Method Declaration Components:
accessModifier returnType methodName(paramList) throws ExceptionList {
// method body
}
// Example:
public int add(int a, int b) {
return a + b;
}
1.12 Method Overloading
Multiple methods with same name but different parameters (number, type, or order of arguments).
📌 Note: Return type alone cannot differentiate overloaded methods — causes ambiguity and compile error.
3 Ways to Overload:
• By number of parameters: mul(int a, int b) vs mul(int a, int b, int c)
• By data type: show(int x) vs show(double x)
• By sequence of types: show(int, char) vs show(char, int)
class Multiply {
void mul(int a, int b) {
[Link]("Two args: " + (a * b));
}
void mul(int a, int b, int c) {
[Link]("Three args: " + (a * b * c));
}
}
// Output: Two args: 60 | Three args: 300
📌 Note: Method Overloading = Static/Compile-time/Early binding (resolved at compile time).
1.13 Constructors
A block of code that initializes newly created objects. Has same name as the class, no return type.
Type Description
Default Constructor Inserted by Java compiler if NO constructor is defined. Has empty body. Not
present in source code.
No-arg Constructor Written by programmer with no parameters. Can have any body. Not same as
default.
Parameterized Takes parameters to initialize object with specific values.
Constructor
// Parameterized Constructor
public class Employee {
int empId; String empName;
Employee(int id, String name) {
[Link] = id;
[Link] = name;
}
}
// Usage: Employee obj = new Employee(101, "Alice");
📌 Note: If you define only a parameterized constructor, calling Employee() (no-arg) will cause a compile error
— compiler does not insert default constructor when any constructor exists.
1.14 Static Keyword
Belongs to the class rather than any instance. Can be applied to: variables, methods, blocks, nested classes.
Static Key Points
Member
Static Single copy shared by all objects. Memory allocated once at class loading. Saves memory.
Variable
Static Method Belongs to class, no object needed to call it. Can only access static data/methods directly.
Cannot use this or super.
Static Block Executes before main() at class loading. Used to initialize static data.
class Counter2 {
static int count = 0; // shared variable
Counter2() { count++; [Link](count); }
}
// new Counter2(); new Counter2(); new Counter2();
// Output: 1 2 3 (increments across all objects)
📌 Note: Why is main() static? — JVM must call main() before any object exists. If non-static, JVM would need
an object first, causing extra memory allocation.
1.15 this Keyword
A reference variable that refers to the current object. 6 usages:
• Refer to current class instance variable (resolve ambiguity with parameters)
• Invoke current class method (implicitly)
• Invoke current class constructor — this()
• Pass as argument in method call
• Pass as argument in constructor call
• Return current class instance from a method
class Student {
int rollno; String name; float fee;
Student(int rollno, String name, float fee) {
[Link] = rollno; // [Link] = instance var
[Link] = name; // name (right) = parameter
[Link] = fee;
}
}
// Without 'this': rollno=rollno assigns parameter to itself → 0 null 0.0
// With 'this': correctly sets instance vars → 111 ankit 5000
MODULE 1 — Question Bank Answers
Q1. Define the Java Development Kit (JDK).
Ans: JDK is a software development environment used to develop and run Java programs. It contains tools
required to write Java programs (compiler javac, application launcher, Appletviewer) and JRE to execute
them. The compiler converts Java source code into bytecode. Multiple JDK versions can be installed on the
same machine. JDK is available for Windows, macOS, Solaris, and Linux.
Q2. List the primary Java buzzwords and their meanings.
Ans: Java has 12 buzzwords: (1) Simple — easy syntax similar to C/C++. (2) Object-Oriented — based on
classes and objects. (3) Portable — programs run on any platform. (4) Platform Independent — bytecode
runs on any OS with JVM (Write Once, Run Anywhere). (5) Secured — no pointers, bytecode verification. (6)
Robust — strong memory management and exception handling. (7) Architecture Neutral — bytecode not
processor-specific. (8) Interpreted — JVM interprets bytecode. (9) High Performance — JIT compiler speeds
execution. (10) Multithreaded — concurrent thread execution. (11) Distributed — designed for distributed
computing. (12) Dynamic — dynamic class loading at runtime.
Q3. What is bytecode in Java?
Ans: Bytecode is the intermediate representation of a Java program produced by the Java compiler (javac). It
is not machine code specific to any OS or processor — instead, it is a platform-neutral binary format (.class
files). The JVM on any platform can interpret this bytecode and execute it, enabling Java's 'Write Once, Run
Anywhere' capability. The JIT compiler converts bytecode to native machine code at runtime for better
performance.
Q4. Define JVM and explain its role.
Ans: JVM (Java Virtual Machine) is an engine that provides a runtime environment to execute Java bytecode.
It converts Java bytecode into machine-specific language. Key roles: (1) Provides platform independence —
same bytecode runs on any OS with a JVM. (2) Contains JIT (Just-In-Time) compiler for faster execution. (3)
Manages memory (heap, stack). (4) Performs garbage collection. (5) Verifies bytecode before execution for
security. JVM is part of JRE.
Q5. List different Java primitive data types.
Ans: Java has 8 primitive data types: (1) boolean — true/false. (2) byte — 8-bit, range -128 to 127. (3) short
— 16-bit, range -32,768 to 32,767. (4) int — 32-bit, default integer type. (5) long — 64-bit, for large numbers
(suffix L). (6) float — 32-bit decimal (suffix f). (7) double — 64-bit decimal, default for decimals. (8) char — 16-
bit Unicode character ('\u0000' to '\uffff').
Q6. State the syntax rules for declaring arrays in Java.
Ans: Array declaration: dataType[] arrayRefVar; (preferred) or dataType arrayRefVar[]; (C-style). Array
creation: arrayRefVar = new dataType[arraySize]; or combined as dataType[] arr = new dataType[size]; or
with initialization: dataType[] arr = {val0, val1, val2}. Indices start from 0. Length accessed via [Link].
Arrays store fixed-size, same-type sequential elements.
Q7. What are control statements in Java? Name any three.
Ans: Control statements control the flow of execution based on conditions. They cause execution to advance
or branch based on program state. Three types: (1) if / if-else / if-else-if / nested-if — conditional branching.
(2) switch-case — multiway branch based on expression value. (3) Loops (while, for, do-while) — repeated
execution. Jump statements include break, continue, and return.
Q8. Define method overloading with a simple example.
Ans: Method overloading means defining multiple methods in a class with the same name but different
parameter lists (different number, type, or order of parameters). It increases code readability and enables
polymorphism. Example: void add(int a, int b) and void add(int a, int b, int c) in the same class — both are
valid and resolved at compile time (static/early binding). Overloading by return type alone is NOT allowed as it
causes ambiguity.
Q9. What is the purpose of a constructor in Java?
Ans: A constructor initializes a newly created object. It has the same name as the class and no return type. It
is automatically invoked when an object is created using new. Types: (1) Default constructor — inserted by
compiler if none defined, empty body. (2) No-arg constructor — written by programmer with no parameters.
(3) Parameterized constructor — accepts arguments to set initial values. If you implement any constructor,
the compiler no longer inserts the default constructor.
Q10. What is the function of the this keyword?
Ans: this is a reference variable pointing to the current object. Uses: (1) Distinguish instance variables from
parameters with same name ([Link] = rollno). (2) Invoke current class method. (3) Invoke current class
constructor using this(). (4) Pass current object as method argument. (5) Pass current object as constructor
argument. (6) Return current instance from a method. It cannot be used in static context.
Q20. Explain the relationship between JVM, JDK, and JRE.
Ans: JDK (Java Development Kit) is the complete development environment containing: (1) Development
tools — compiler (javac), debugger, Applet Viewer. (2) JRE — Java Runtime Environment. JRE is a subset of
JDK containing: (1) Class libraries and frameworks. (2) JVM — Java Virtual Machine. JVM is the smallest unit
— it executes bytecode and converts it to machine code. Hierarchy: JDK ⊃ JRE ⊃ JVM. A programmer
needs JDK to write and run programs. An end-user needs only JRE to run programs. JVM is the platform-
specific component that makes Java platform-independent.
Q21. Describe how Java achieves platform independence.
Ans: Java achieves platform independence through bytecode. When you write Java code, the Java compiler
(javac) compiles it into bytecode (.class files) — not into machine-specific code. This bytecode is a neutral
intermediate format. Any machine with a JVM (Java Virtual Machine) installed can then interpret and execute
this bytecode, regardless of the underlying OS or processor. The JVM is platform-specific (different for
Windows, Linux, Mac), but the bytecode is the same everywhere. This is the 'Write Once, Run Anywhere'
principle. The JIT compiler inside JVM also converts bytecode to native code at runtime for speed.
Q22. Explain how arrays are stored and accessed in Java.
Ans: Arrays in Java are objects stored in heap memory. Declaration: double[] myList; creates a reference
variable. Creation: myList = new double[10]; allocates memory for 10 doubles on the heap and returns a
reference. The reference variable (myList) stores the address of this heap memory. Elements are accessed
via 0-based indices: myList[0] through myList[9]. Length is accessed via [Link]. Arrays can be
initialized at declaration: int[] arr = {1, 2, 3}; — a new array is created and values are copied. For primitive
types, elements are stored directly; for object arrays, elements store references.
Q23. Illustrate the use of command-line arguments in Java with an example.
Ans: Command-line arguments are passed to main(String[] args) when running the program. They are
always Strings. Example: class Demo { public static void main(String[] b) { [Link]("Arg 1: " + b[0]);
[Link]("Arg 2: " + b[1]); } } Run as: java Demo apple orange. Output: Arg 1: apple / Arg 2: orange.
Key points: [Link] gives number of arguments; used to pass configuration values at startup; any number
of arguments can be specified; all are captured as String type.
MODULE 2: Inheritance and Interfacing
2.1 Inheritance
Inheritance allows a class to acquire all properties and behaviors of a parent class. Represents IS-A relationship
(also called parent-child or superclass-subclass relationship).
• The class being inherited = Superclass (Base class / Parent class)
• The class doing the inheriting = Subclass (Derived class / Child class / Extended class)
• Keyword: extends
class Subclass_name extends Superclass_name {
// additional methods and fields
}
Why use Inheritance?
• Code Reusability — use parent's methods without rewriting
• Method Overriding — enables runtime polymorphism
• Extensibility — extend parent logic in child class
Types of Inheritance in Java:
Type Description Support in Java
Single One subclass from one superclass (A → B) Supported with classes
Multilevel Chain: A → B → C (B is subclass of A and Supported with classes
superclass of C)
Hierarchical Multiple subclasses from one parent (A → Supported with classes
B, A → C)
Multiple One class from multiple parents NOT supported with classes (diamond
problem); use interfaces
Hybrid Combination of multiple types NOT supported with classes; use interfaces
Single Inheritance Example:
class Vehicle {
Vehicle() { [Link]("This is a Vehicle"); }
}
class Car extends Vehicle {
Car() { [Link]("This Vehicle is Car"); }
}
// new Car() → Output: This is a Vehicle / This Vehicle is Car
Member Access and Inheritance:
📌 Note: Subclasses inherit all non-private members. Private members are NOT accessible in subclasses.
Superclass Variable Can Reference Subclass Object:
Box plainbox = new Box();
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
plainbox = weightbox; // valid! BoxWeight IS-A Box
// plainbox can call Box methods but NOT BoxWeight-specific ones
super Keyword — 3 Uses:
• 1. Access parent class instance variable (when child has same-named field):
[Link]([Link]); // parent's color
• 2. Invoke parent class method (when overridden):
[Link](); // calls parent's eat()
• 3. Invoke parent class constructor (must be FIRST statement in child constructor):
super(w, h, d); // calls parent constructor with args
Constructor Call Order in Inheritance:
Constructors are called from superclass to subclass (top-down). super() is implicitly inserted if not written.
// class C extends B extends A
// new C() → Output: Inside A's constructor / Inside B's constructor / Inside C's
constructor
2.2 Method Overriding
When a subclass defines a method with the SAME name and SAME type signature as a superclass method, it
overrides it.
• Used for runtime polymorphism (method resolved at runtime based on object type).
• To call the overridden (parent) version inside child: use [Link]()
• If signatures differ → overloading, NOT overriding
class A {
void show() { [Link]("A's show"); }
}
class B extends A {
@Override
void show() { [Link]("B's show"); }
}
// B obj = new B(); [Link](); → "B's show"
// [Link]() inside B would print → "A's show"
Dynamic Method Dispatch (Runtime Polymorphism):
ABC obj = new Demo(); // parent ref → child object
[Link](); // calls CHILD's disp() at runtime
📌 Note: The type of OBJECT (not reference) determines which method is called at runtime. Cannot call
methods newly declared only in child class via parent reference.
2.3 Annotations
Metadata that provides information about code without changing its behavior. Start with '@'. Used by compiler,
build tools, and frameworks.
Annotation Purpose
@Override Confirms a method overrides a superclass method; compiler catches errors if not.
@Deprecated Marks method/class as outdated; IDEs show warning when used.
@SuppressWarnings Tells compiler to ignore specific warnings (e.g., 'unchecked').
@Documented Annotation included in generated Javadoc.
@Target Specifies where annotation can be applied (class, method, field...).
@Inherited Allows subclass to inherit annotation from parent.
@FunctionalInterface Indicates interface with single abstract method (for lambda expressions).
5 Categories of Annotations:
• Marker Annotations — no elements; presence alone is the signal. e.g. @TestAnnotation()
• Single Value Annotations — one element, shorthand notation. e.g. @TestAnnotation("testing")
• Full Annotations — multiple key-value pairs. e.g. @TestAnnotation(owner="Rahul", value="Geeks")
• Type Annotations (Java 8+) — annotate type variables, generics, return types. Uses
@Target(ElementType.TYPE_USE)
• Repeating Annotations — same annotation applied multiple times. Declared with @Repeatable
// Custom Annotation Syntax
@interface AnnotationName {
DataType methodName() default value;
}
2.4 Static Members
Belong to the class; accessible without creating an instance. Applied to variables, methods, blocks, nested
classes.
// Static Method
public class MyClass {
public static void sample() { [Link]("Hello"); }
public static void main(String args[]) {
[Link](); // no object needed
}
}
// Static Field
public static int data = 20;
[Link]([Link]); // access via class name
// Static Block — runs before main()
static { [Link]("Static block runs first"); }
2.5 Inner Classes
A class declared inside another class. Inner class has access to ALL members (including private) of the outer
class.
Type Description
Member Inner Class Non-static class at class level. Instantiated via: [Link] inner = new Outer().new
Inner();
Method-Local Inner Defined inside a method. Can access effectively final local variables (Java 8+).
Class Cannot be private/protected/static.
Static Nested Class Static class inside another. Does NOT access instance members; only static
members. Instantiated via: new [Link]();
Anonymous Inner Unnamed class defined and instantiated in a single expression. Used for one-time
Class interface implementations or overrides.
// Member Inner Class Example
class Outer {
int outer_x = 100;
class Inner {
void display() {
[Link]("outer_x = " + outer_x); // direct access
}
}
}
// Usage: Outer outer = new Outer(); [Link]();
// Or: [Link] inner = new Outer().new Inner(); [Link]();
2.6 Abstract Classes
A class that CANNOT be instantiated; designed to be extended. Declared with abstract keyword. Enables partial
abstraction.
• May contain abstract methods (no body) AND concrete methods (with body)
• Can have constructors, instance variables, static/final methods
• All subclasses MUST implement all abstract methods — or be abstract themselves
• Abstract reference variable is allowed: Figure figref; is valid
abstract class Shape {
String color;
Shape(String color) { [Link] = color; } // constructor
abstract double area(); // abstract method — no body
void getColor() { // concrete method
[Link]("Color: " + color);
}
}
class Circle extends Shape {
int radius;
Circle(String color, int r) { super(color); [Link] = r; }
double area() { return 3.14 * radius * radius; }
}
// Shape s = new Shape(); // ERROR — cannot instantiate abstract class
// Shape s = new Circle("Red", 5); // OK — polymorphism
2.7 final Keyword
Restricts modification. Applied to variables, methods, and classes.
Context Effect
final Becomes a constant — value cannot be changed after initialization
variable
final Cannot be overridden in any subclass
method
final class Cannot be subclassed/extended. All its methods are implicitly final. Cannot be both abstract
and final.
// final method
class A { final void meth() { [Link]("Final method"); } }
class B extends A { void meth() { } } // COMPILE ERROR
// final class
final class A { }
class B extends A { } // COMPILE ERROR — cannot subclass A
Early Binding vs Late Binding:
• Early Binding (Static): resolved at compile time. All static, private, and final methods use early binding.
• Late Binding (Dynamic): resolved at runtime. Method overriding is late binding — actual object type
determines method.
2.8 The Object Class
The root of Java class hierarchy. Every class extends Object directly or indirectly (from [Link]). Provides
essential shared methods.
Method Purpose
toString() Returns String representation of object. Override to provide custom output.
equals(Object obj) Compares objects for equality. Override to define content-based equality.
hashCode() Returns hash value (integer). If equals() returns true for two objects, their
hashCode() MUST be equal.
getClass() Returns the runtime class of the object. Cannot be overridden (final).
clone() Creates shallow copy. Class must implement Cloneable or
CloneNotSupportedException is thrown.
finalize() Called by GC just before object is destroyed. Discouraged in modern Java.
wait() / notify() / Thread communication methods for concurrent programming.
notifyAll()
class Student {
String name = "Vishnu"; int age = 21;
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
}
// Output: Student{name='Vishnu', age=21}
2.9 Interfaces
An interface is an abstract type that defines a contract — what a class MUST do (not how). Enables abstraction
and multiple inheritance.
• All variables in interface are public static final by default
• All methods are public abstract by default (before Java 8)
• A class implements an interface with the implements keyword
• A class can implement multiple interfaces — this is how Java achieves multiple inheritance
• An interface can extend another interface using extends
interface testInterface {
final int a = 10; // public static final
void display(); // public abstract
}
class TestClass implements testInterface {
public void display() { [Link]("Geek"); }
}
// Output: Geek (then: 10 for t.a)
Multiple Inheritance via Interfaces:
interface Add { int add(int a, int b); }
interface Sub { int sub(int a, int b); }
class Cal implements Add, Sub {
public int add(int a, int b) { return a + b; }
public int sub(int a, int b) { return a - b; }
}
New Features Added in JDK 8 (Interfaces):
• Default Methods — methods with a body inside interface; useful for backward compatibility
• Static Methods — called via interface name; not inherited by implementing classes
• Functional Interfaces — single abstract method; used with lambda expressions (@FunctionalInterface)
New Features Added in JDK 9 (Interfaces):
• Private Methods — internal helper methods; not accessible to implementing classes
Class vs Interface:
Class Interface
Can have concrete methods Only abstract methods (before Java 8)
Can have constructors Cannot have constructors
Variables can be any access type Variables are public static final only
Single inheritance (extends) Multiple inheritance (implements many)
Instantiated with new Cannot be instantiated directly
Use for real-world entities with state Use for contracts/capabilities across unrelated classes
2.10 Package Fundamentals
A package is a namespace that groups related classes, interfaces, and sub-packages. Like a folder in a file
system.
Benefits of Packages:
• Avoids naming conflicts (same class name in different packages)
• Provides access control via modifiers
• Enables code reusability and modularity
• Organizes large codebases
Types of Packages:
• Built-in Packages — part of Java API ([Link], [Link], [Link], [Link], [Link])
• User-defined Packages — created by programmer using package keyword
Built-in Package Contents
[Link] Auto-imported. Primitive types, String, Math, Object, System, Thread.
[Link] Input/output: FileInputStream, FileOutputStream, FileReader, FileWriter.
[Link] Data structures: ArrayList, HashMap, LinkedList, Date, Calendar, Scanner.
[Link] Applet creation classes.
[Link] GUI components.
Using Built-in Packages:
import [Link]; // single class
import [Link].*; // entire package
Scanner myObj = new Scanner([Link]);
String userName = [Link]();
Creating User-Defined Packages:
// File: FirstPackage/[Link]
package FirstPackage;
class Welcome {
public static void main(String[] args) {
[Link]("First Program");
}
}
// Compile: javac -d . [Link]
// Run: java [Link]
// Importing user-defined package
import data.*;
class Main {
public static void main(String args[]) {
Demo d = new Demo();
[Link](); [Link]();
}
}
Access Modifiers and Package Protection:
Modifier Same Class Same Package Subclass Outside Non-subclass Outside
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
2.11 Reflection
A feature that allows a running Java program to examine and manipulate its own structure (classes, methods,
fields) at runtime.
• Part of [Link] package.
• Allows examining class names, method names, parameter types, return types.
• Does not change program behavior — only inspects/manipulates metadata.
• Used in JavaBeans, frameworks, IDEs, and testing tools.
3 Steps to Use Reflection:
• Step 1 — Get Class object: Class c = [Link]("[Link]"); or [Link] or [Link]
• Step 2 — Call method: Method m[] = [Link](); (declared methods only) or getMethods()
(includes inherited)
• Step 3 — Use reflection API to examine/manipulate information
import [Link].*;
public class DumpMethods {
public static void main(String args[]) {
try {
Class c = [Link](args[0]);
Method m[] = [Link]();
for (int i = 0; i < [Link]; i++)
[Link](m[i].toString());
} catch (Throwable e) { [Link](e); }
}
}
// Run: java DumpMethods [Link]
// Output: prints all method signatures of Stack class
// Simulate instanceof using reflection:
Class cls = [Link]("A");
boolean b1 = [Link](new Integer(37)); // false
boolean b2 = [Link](new A()); // true
MODULE 2 — Question Bank Answers
Q1. What is inheritance in Java? Explain with an example.
Ans: Inheritance is a mechanism where one class (subclass) acquires all properties and behaviors of another
class (superclass), representing an IS-A relationship. It promotes code reusability and enables runtime
polymorphism. Syntax: class Dog extends Animal { }. Example: class Vehicle { void run()
{ [Link]("running"); } } class Car extends Vehicle { }. A Car object can call run() from Vehicle
without redefining it.
Q2. What are the advantages of inheritance in OOP?
Ans: Advantages: (1) Code Reusability — public methods of the base class are reused without rewriting. (2)
Extensibility — subclass extends parent logic with new fields/methods. (3) Method Overriding — enables
runtime polymorphism. (4) Better code organization — hierarchical grouping of related classes. (5) Flexibility
— superclass reference can hold subclass objects (polymorphism). Disadvantages: Complexity increases
with deep hierarchies; tight coupling between parent and child makes changes difficult.
Q3. Explain the different types of inheritance supported in Java.
Ans: Java supports: (1) Single Inheritance — one subclass extends one superclass (A → B). (2) Multilevel
Inheritance — a chain where B extends A and C extends B (A → B → C). (3) Hierarchical Inheritance —
multiple subclasses from one parent (A → B, A → C). Java does NOT support Multiple Inheritance with
classes (one class inheriting multiple parents) to avoid the diamond problem — ambiguity when two parents
have the same method. It also doesn't directly support Hybrid Inheritance with classes. Both multiple and
hybrid can be achieved through interfaces.
Q4. Why does Java not support multiple inheritance using classes?
Ans: Java avoids multiple inheritance with classes due to the 'diamond problem': if class C inherits from both
A and B, and A and B both define the same method, it creates ambiguity about which version C should use.
This leads to complex, error-prone code. Solution: Java allows a class to implement multiple interfaces,
achieving multiple inheritance of behavior. Since (pre-Java 8) interfaces only had abstract methods, no
ambiguity arose. From Java 8 onwards, if both interfaces provide the same default method, the implementing
class must explicitly override it.
Q5. What is the purpose of the super keyword?
Ans: super is a reference variable in Java that refers to the immediate parent class. It has 3 uses: (1)
[Link] — access parent class field when child has same-named field (e.g., [Link]). (2)
[Link]() — invoke parent class method when it is overridden in child (e.g., [Link]()). (3)
super() — invoke parent class constructor; must be the FIRST statement in the child constructor. Used to
pass arguments to parent's parameterized constructor.
Q6. Write a Java program where class Animal is inherited by class Dog.
Ans: class Animal { void eat() { [Link]("eating..."); } } class Dog extends Animal { void bark()
{ [Link]("barking..."); } } class Test { public static void main(String[] args) { Dog d = new Dog();
[Link](); [Link](); } } Output: eating... / barking... — Dog inherits eat() from Animal without rewriting it.
Q9. What is method overriding in Java? What are the rules for method overriding?
Ans: Method overriding occurs when a subclass defines a method with the SAME name and SAME type
signature (same parameters and return type) as a method in its superclass. It enables runtime polymorphism.
Rules: (1) Method name and parameters must be identical. (2) Return type must be same or covariant. (3)
Access modifier cannot be more restrictive than parent's. (4) Only inherited (non-static, non-final, non-private)
methods can be overridden. (5) @Override annotation should be used. (6) [Link]() can call the
overridden parent version.
Q10. What is the difference between method overriding and method overloading?
Ans: Overloading: same method name, different parameter list (number/type/order), resolved at COMPILE
time (static/early binding), in the same class. Overriding: same method name AND same parameter list,
resolved at RUNTIME (dynamic/late binding), in superclass-subclass relationship. Overloading is a compile-
time polymorphism; overriding is runtime polymorphism. Return type alone cannot differentiate overloaded
methods. Static and private methods cannot be overridden.
Q11. What happens if the overridden method is declared final? Can static methods be overridden?
Ans: If a method is declared final, it CANNOT be overridden in any subclass — attempting to do so causes a
compile-time error. Final methods use early (static) binding. Static methods cannot be overridden — they can
only be hidden. If a subclass defines a static method with same signature, it hides the parent's method rather
than overriding it. When called via parent reference, parent's static method executes; no runtime
polymorphism.
Q14. What are annotations in Java?
Ans: Annotations are a form of metadata in Java that provide information about the code (to compiler, build
tools, or frameworks) without changing the program's actual behavior. They start with '@'. They can be
applied to classes, methods, fields, constructors, etc. Built-in examples: @Override (ensures method
overrides parent), @Deprecated (marks obsolete code), @SuppressWarnings (silences compiler warnings).
Categories: Marker, Single-value, Full, Type, and Repeating annotations. Custom annotations are created
using @interface.
Q15. What is the purpose of @Override annotation? Explain @Deprecated annotation.
Ans: @Override: Placed before a method to tell the compiler the method is intended to override a superclass
method. If the method does NOT actually override (e.g., wrong signature), the compiler reports an error —
preventing subtle bugs. It is not mandatory but strongly recommended. @Deprecated: Marks a class, method,
or field as outdated/discouraged from use. IDEs show a warning/strikethrough when deprecated members are
used. Useful when maintaining APIs to signal that something will be removed in future versions.
Q19. What is a static variable in Java?
Ans: A static variable (class variable) is declared with the static keyword inside a class but outside any
method. Unlike instance variables, only ONE copy exists for the entire class — shared by all objects. Memory
is allocated once when the class is loaded. Used for properties common to all objects (e.g., college name for
all students). Accessed via class name: [Link]. Changing it via one object affects all:
[Link]++ is reflected in all instances.
Q20. What is a static method? Can static methods access instance variables? Why?
Ans: A static method belongs to the class rather than any object. It can be called without creating an
instance: [Link](). Static methods can only directly access static data members and static
methods — NOT instance variables or non-static methods. This is because at the time of the static method
call, no object may exist, so instance variables (which are per-object) are undefined. this and super cannot be
used inside static methods for the same reason.
Q21. What is a static block in Java? What is the difference between static and non-static members?
Ans: A static block (static { }) is executed automatically by JVM before the main() method when the class is
first loaded. Used to initialize static data members. Example: static { college = "NHCE"; }. Difference — Static
members: belong to the class; single copy shared; accessible without object; loaded when class loads. Non-
static members: belong to each object instance; each object gets its own copy; must create object to access;
loaded when object is created.
Q24. What is an inner class in Java? Explain the types of inner classes.
Ans: An inner class is a class declared inside another class. The inner class has access to all members
(including private) of the outer class. Types: (1) Member Inner Class — non-static at class level; needs outer
instance to instantiate. (2) Method-Local Inner Class — inside a method; can access effectively final local
variables. (3) Static Nested Class — static; no access to instance members; instantiated without outer
instance. (4) Anonymous Inner Class — unnamed; defined and instantiated at the same point; used for one-
time use implementations.
Q29. What is an abstract class in Java? What is an abstract method?
Ans: An abstract class is a class declared with the abstract keyword that CANNOT be instantiated directly. It
is designed to be subclassed. An abstract method is a method declared without a body (abstract returnType
methodName();) — subclasses MUST provide its implementation. An abstract class can contain both abstract
and concrete methods, constructors, static methods, and instance variables. A reference variable of abstract
type IS allowed (for polymorphism). A class that does not implement all abstract methods must itself be
declared abstract.
Q31. What is the difference between abstract class and interface?
Ans: Abstract Class: can have both abstract and concrete methods; can have instance variables; can have
constructors; a class can extend only ONE abstract class; cannot achieve 100% abstraction (may have
concrete methods). Interface: only abstract methods by default (pre-Java 8); variables are public static final
only; no constructors; a class can implement MULTIPLE interfaces — enabling multiple inheritance; achieves
100% abstraction. Use abstract class when classes share common behavior. Use interface when unrelated
classes need to follow a common contract.
Q34. What is a final variable? What is a final method?
Ans: A final variable is a constant — once assigned, its value cannot be changed. Example: final int MAX =
100; attempting MAX = 200 causes a compile error. A final method cannot be overridden by any subclass.
Declaring a method final enables early (static) binding — the compiler resolves the call at compile time. This
provides security (no one can alter behavior) and can improve performance. final methods are still inherited
but cannot be redefined.
Q35. What is a final class? Why is the String class declared final?
Ans: A final class cannot be subclassed/extended. All its methods are implicitly final. Example: final class A
{ } and class B extends A { } causes a compile error. A class cannot be both abstract and final. The String
class is final to ensure immutability and security — if String could be subclassed, a subclass could override
methods and change behavior (e.g., equals(), hashCode()), breaking assumptions made throughout the JDK.
Keeping String final guarantees consistent, predictable behavior.
Q39. What is the Object class in Java? Why is it the root class?
Ans: The Object class in [Link] is the root of the entire Java class hierarchy. Every class in Java either
explicitly extends another class or implicitly extends Object. It is the root class because: (1) It provides
fundamental methods every Java object needs (toString, equals, hashCode, clone, getClass, wait, notify). (2)
It allows any Java class to be referenced via Object type. (3) It defines the contract for object comparison,
hashing, and cloning — foundational for collections and frameworks.
Q45. What is an interface in Java? What are the features of interfaces?
Ans: An interface defines a contract — a set of abstract methods a class must implement. Declared with
interface keyword. Features: (1) All methods are public abstract by default. (2) All variables are public static
final. (3) Cannot be instantiated. (4) A class implements it with implements keyword. (5) Supports multiple
inheritance (a class can implement multiple interfaces). (6) Interfaces can extend other interfaces. Java 8
additions: default methods, static methods, functional interfaces. Java 9 addition: private methods.
Q49. What is a package in Java? What are the advantages of packages?
Ans: A package is a namespace grouping related classes, interfaces, and sub-packages — like folders in a
file system. Advantages: (1) Avoids name conflicts (same class name in different packages is valid). (2)
Access control — public, protected, default modifiers define visibility across packages. (3) Code organization
and maintainability — related classes grouped together. (4) Reusability — packaged code imported and used
anywhere. (5) Modular programming — enables separation of concerns. Types: Built-in ([Link], [Link],
[Link]...) and User-defined.
Q53. What is reflection in Java?
Ans: Reflection is a Java API that allows a running program to inspect and manipulate its own structure —
classes, methods, fields, constructors — at runtime. Located in [Link] package. Uses: examine
class names, method signatures, parameter types; dynamically invoke methods; inspect annotations at
runtime. Used heavily in frameworks (Spring, Hibernate), IDEs, testing tools (JUnit), and JavaBeans. 3 steps:
(1) Get Class object via [Link](); (2) call getDeclaredMethods() or getFields(); (3) use the reflection
API. Limitation: slower than direct calls; breaks encapsulation if misused.