0% found this document useful (0 votes)
1 views29 pages

Java OOP Notes Engineering

This document provides short notes on Java programming for engineering students, covering key concepts such as Object-Oriented Programming (OOP) principles, the Java Development Kit (JDK), data types, variables, arrays, and operators. It includes explanations of core OOP principles like encapsulation, abstraction, inheritance, and polymorphism, as well as details on Java's architecture and features. Additionally, it outlines variable types, array handling, and various operators used in Java.

Uploaded by

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

Java OOP Notes Engineering

This document provides short notes on Java programming for engineering students, covering key concepts such as Object-Oriented Programming (OOP) principles, the Java Development Kit (JDK), data types, variables, arrays, and operators. It includes explanations of core OOP principles like encapsulation, abstraction, inheritance, and polymorphism, as well as details on Java's architecture and features. Additionally, it outlines variable types, array handling, and various operators used in Java.

Uploaded by

sarandevi.viji
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA PROGRAMMING

Short Notes for Engineering Students


Reference: Herbert Schildt & Danny Coward – Java: The Complete Reference, 13th Edition, McGraw Hill, 2024

Unit Syllabus: Principles of OOP | JDK | Data Types, Variables & Arrays | Operators | Control Statements | Classes &
Objects | Constructors | Method Overriding | Access Specifiers | Static Members | Inheritance

1. PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING (OOP)


▶ 13-Mark Notes

Introduction to OOP
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data
(objects) rather than functions and logic. Java is a purely object-oriented language that implements all core OOP
principles.

1.1 Core Principles of OOP


1. Encapsulation
Encapsulation is the process of wrapping data (variables) and methods (functions) together into a single unit
called a class. It restricts direct access to internal details and exposes only necessary parts through access
specifiers.
• Protects data from unauthorized access
• Achieved using private variables + public getters/setters
class BankAccount {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amt) { balance += amt; }
}

2. Abstraction
Abstraction hides complex implementation details and shows only essential features. In Java, abstraction is
achieved using abstract classes and interfaces.
• Abstract class: may have both abstract and concrete methods
• Interface: provides 100% abstraction (before Java 8)
abstract class Shape {
abstract void draw(); // no implementation
}

3. Inheritance
Inheritance allows a class (child/subclass) to acquire properties and methods of another class
(parent/superclass). It promotes code reuse and establishes an 'IS-A' relationship.
• Java supports single, multilevel, and hierarchical inheritance
• Multiple inheritance via classes is NOT supported; achieved through interfaces
class Animal { void eat() { ... } }
class Dog extends Animal { void bark() { ... } }
4. Polymorphism
Polymorphism means 'many forms'. The same method name can behave differently in different contexts. Java
supports two types:
• Compile-time (Static) Polymorphism – Method Overloading: same method name, different parameters
• Runtime (Dynamic) Polymorphism – Method Overriding: subclass redefines parent method
class Calculator {
int add(int a, int b) { return a+b; }
double add(double a, double b) { return a+b; } // Overloading
}

5. Object & Class


A class is a blueprint or template for creating objects. An object is an instance of a class that has state (fields)
and behavior (methods). Everything in Java revolves around objects.

1.2 Advantages of OOP


• Modularity – Code is organized into classes
• Reusability – Inheritance reduces code duplication
• Maintainability – Easy to update and maintain
• Scalability – Easy to add new features without affecting existing code
• Security – Encapsulation protects sensitive data
▶ 3-Mark Questions & Answers

Q1. Define OOP and list its principles.


OOP is a paradigm that organizes programs using objects. The four main principles are: Encapsulation,
Abstraction, Inheritance, and Polymorphism. Java strictly follows all OOP principles.

Q2. Differentiate Overloading and Overriding.


Method Overloading (compile-time polymorphism): same method name with different parameters in the same
class. Method Overriding (runtime polymorphism): subclass redefines the parent class method with the same
signature.

Q3. What is Encapsulation? Give example.


Encapsulation wraps data and methods into a class, hiding internal details. Example: A class with private fields
and public getter/setter methods like getBalance() in a BankAccount class.
▶ MCQ Questions
No Question Options Answer
.
1. Which OOP concept is used to hide internal implementation a) Inheritance b) Abstraction
details? b) Abstraction
c) Polymorphism
d) Encapsulation
2. Which type of inheritance is NOT directly supported by Java a) Single c) Multiple
classes? b) Multilevel
c) Multiple
d) Hierarchical
3. Method Overloading is an example of which polymorphism? a) Runtime b) Compile-time
b) Compile-time
c) Dynamic
d) None
4. Which principle wraps data and methods together? a) Abstraction c)
b) Polymorphism Encapsulation
c) Encapsulation
d) Inheritance
5. In Java, interfaces provide which level of abstraction? a) Partial c) 100%
b) 50%
c) 100%
d) No abstraction
2. JAVA DEVELOPMENT KIT (JDK)
▶ 13-Mark Notes

Introduction
Java Development Kit (JDK) is a software development environment used to develop Java applications. It
includes the tools necessary for compiling, debugging, and running Java programs.

2.1 Java Architecture


• Java Source Code (.java) → Compiled by javac → Bytecode (.class) → Executed by JVM
Java's 'Write Once, Run Anywhere' (WORA) is possible because bytecode runs on any platform with a JVM.

2.2 Components of JDK


JDK (Java Development Kit)
• Complete development toolkit for writing, compiling, and running Java programs
• Includes: javac (compiler), java (runtime), javadoc, jar, jdb (debugger)

JRE (Java Runtime Environment)


• Subset of JDK; used only for running Java programs, not compiling
• Contains: JVM + class libraries + other supporting files

JVM (Java Virtual Machine)


• Abstract machine that executes Java bytecode
• Handles memory management, garbage collection, and security
• JVM is platform-dependent but bytecode is platform-independent

2.3 Java Platform Editions


• Java SE (Standard Edition) – Core language for desktop/server applications
• Java EE (Enterprise Edition) – Web, enterprise applications (Servlets, JSP)
• Java ME (Micro Edition) – Mobile and embedded systems

2.4 Important JDK Tools


javac – Java compiler; converts .java source to .class bytecode
java – JVM launcher; executes compiled bytecode
javadoc – Generates HTML documentation from source code comments
jar – Packages multiple .class files into a single archive (.jar file)
jdb – Java Debugger for debugging programs

2.5 Java Program Execution Process


• Step 1: Write source code in .java file
• Step 2: Compile using javac → generates .class file (bytecode)
• Step 3: JVM interprets/compiles bytecode using JIT compiler
• Step 4: Output is displayed
// First Java Program
public class Hello {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
// Compile: javac [Link]
// Run: java Hello

2.6 Features of Java


• Simple – Clean syntax derived from C/C++
• Platform Independent – Bytecode runs on any JVM
• Object-Oriented – Everything is an object
• Robust – Strong exception handling and type checking
• Secure – No pointers; JVM security sandbox
• Multithreaded – Supports concurrent execution
• Distributed – Built-in networking support ([Link])
• Garbage Collected – Automatic memory management
▶ 3-Mark Questions & Answers

Q1. What is JDK? How is it different from JRE?


JDK (Java Development Kit) includes all tools to develop, compile, and run Java programs. JRE (Java Runtime
Environment) is a subset that only allows running Java programs. JDK = JRE + development tools like javac and
jdb.

Q2. Explain the role of JVM.


JVM (Java Virtual Machine) executes Java bytecode. It provides platform independence by interpreting
bytecode, manages memory through garbage collection, and provides security by running code in a sandbox
environment.

Q3. List any three features of Java.


(1) Platform Independence – WORA using bytecode and JVM. (2) Object-Oriented – Supports encapsulation,
inheritance, polymorphism. (3) Robust – Strong type checking, exception handling, and automatic garbage
collection.
▶ MCQ Questions
No Question Options Answer
.
1. What does JDK stand for? a) Java Design Kit b) Java
b) Java Development
Development Kit Kit
c) Java Debug Kit
d) Java Deployment
Kit
2. Which command is used to compile a Java program? a) java c) javac
b) jvm
c) javac
d) jar
3. JVM executes which type of code? a) Source code c) Bytecode
b) Machine code
c) Bytecode
d) Assembly code
4. Which Java edition is used for mobile applications? a) Java SE c) Java ME
b) Java EE
c) Java ME
d) Java FX
5. JRE is a subset of? a) JVM b) JDK
b) JDK
c) javac
d) javadoc
3. DATA TYPES, VARIABLES AND ARRAYS
▶ 13-Mark Notes

3.1 Data Types in Java


Java is a strongly-typed language – every variable must be declared with a type. Data types define what kind of
value a variable can hold.

Primitive Data Types (8 types)


Type Size Range Example
byte 1 byte -128 to 127 byte b = 10;
short 2 bytes -32768 to 32767 short s = 500;
int 4 bytes -2^31 to 2^31-1 int n = 1000;
long 8 bytes -2^63 to 2^63-1 long l = 9999L;
float 4 bytes 3.4e-38 to 3.4e+38 float f = 3.14f;
double 8 bytes 1.7e-308 to 1.7e+308 double d = 3.14;
char 2 bytes 0 to 65535 (Unicode) char c = 'A';
boolean 1 bit true / false boolean b = true;

Non-Primitive Data Types


• String – Sequence of characters: String name = "Java";
• Arrays – Collection of same type elements
• Classes, Interfaces – User-defined reference types

3.2 Variables in Java


A variable is a named memory location that stores a value. In Java, variables must be declared before use.

Types of Variables
• Local Variable – Declared inside a method; accessible only within that method
• Instance Variable – Declared inside class but outside methods; each object has its own copy
• Static Variable (Class Variable) – Declared with 'static'; shared among all objects of the class
class Demo {
int x = 5; // instance variable
static int count = 0; // static variable
void show() {
int local = 10; // local variable
}
}

Variable Declaration & Initialization


int age; // declaration
age = 20; // initialization
int marks = 85; // declaration + initialization

3.3 Arrays in Java


An array is a collection of variables of the same data type stored in contiguous memory. Array indices start from
0 in Java.

1D Array (Single-Dimensional)
int[] arr = new int[5]; // declaration
int[] arr = {10, 20, 30, 40, 50}; // initialization
[Link](arr[0]); // access: prints 10

2D Array (Multi-Dimensional)
int[][] matrix = new int[3][3];
int[][] m = {{1,2,3},{4,5,6},{7,8,9}};
[Link](m[1][2]); // prints 6

Array Operations
• [Link] – returns size of array
• [Link](arr) – sorts array using [Link]
• [Link](arr, val) – fills array with given value
• [Link]() – copies array elements

Iterating Arrays
for (int i = 0; i < [Link]; i++) {
[Link](arr[i]);
}
// Enhanced for loop
for (int x : arr) { [Link](x); }

Jagged Arrays
Java supports jagged arrays where rows can have different lengths.
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[3];
▶ 3-Mark Questions & Answers

Q1. List the primitive data types in Java.


Java has 8 primitive types: byte (1B), short (2B), int (4B), long (8B), float (4B), double (8B), char (2B), and boolean
(1 bit). They store actual values, not references.

Q2. What is the difference between local and instance variables?


Local variables are declared inside methods and accessible only within that method; they have no default value.
Instance variables are declared in a class outside methods; each object has its own copy and they have default
values (0, null, false).

Q3. How are arrays declared and initialized in Java?


Arrays in Java: Declaration: int[] arr = new int[5]; Initialization: int[] arr = {1,2,3,4,5}; Access: arr[0]. Arrays are
objects with a .length property; index starts at 0.
▶ MCQ Questions
No Question Options Answer
.
1. What is the default value of an int variable in Java? a) null b) 0
b) 0
c) -1
d) undefined
2. Which data type is used to store a single character in Java? a) String b) char
b) char
c) byte
d) int
3. Array index in Java starts from? a) 1 c) 0
b) -1
c) 0
d) Depends on type
4. What is the size of a double data type in Java? a) 4 bytes c) 8 bytes
b) 2 bytes
c) 8 bytes
d) 16 bytes
5. Which keyword is used to find the length of an array? a) size() c) length
b) count
c) length
d) len
4. OPERATORS IN JAVA
▶ 13-Mark Notes
Operators are special symbols used to perform operations on variables and values. Java supports a rich set of
operators.

4.1 Types of Operators


1. Arithmetic Operators
Used for mathematical operations: + (add), - (subtract), * (multiply), / (divide), % (modulus)
int a=10, b=3;
[Link](a+b); // 13
[Link](a%b); // 1

2. Relational (Comparison) Operators


Used to compare two values; result is boolean: ==, !=, >, <, >=, <=
[Link](a > b); // true
[Link](a == b); // false

3. Logical Operators
Used with boolean expressions: && (AND), || (OR), ! (NOT)
boolean x=true, y=false;
[Link](x && y); // false
[Link](x || y); // true

4. Assignment Operators
Assign values: =, +=, -=, *=, /=, %=
int n = 10;
n += 5; // n = n + 5 = 15

5. Bitwise Operators
Operate on bits: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift), >>> (unsigned right shift)
int a=5; // 0101 in binary
int b=3; // 0011 in binary
[Link](a & b); // 0001 = 1

6. Unary Operators
+, -, ++, --, ! – operate on a single operand
int x = 5;
[Link](++x); // Pre-increment: 6
[Link](x++); // Post-increment: prints 6, x becomes 7

7. Ternary Operator
Short form of if-else: condition ? value_if_true : value_if_false
int a=10, b=20;
int max = (a > b) ? a : b; // max = 20

8. instanceof Operator
Tests whether an object is an instance of a given class or interface.
String s = "Java";
[Link](s instanceof String); // true

4.2 Operator Precedence (High to Low)


• 1. Postfix: expr++, expr--
• 2. Unary: ++expr, -expr, !
• 3. Multiplicative: *, /, %
• 4. Additive: +, -
• 5. Shift: <<, >>
• 6. Relational: <, >, <=, >=, instanceof
• 7. Equality: ==, !=
• 8. Bitwise: &, ^, |
• 9. Logical: &&, ||
• 10. Ternary: ?:
• 11. Assignment: =, +=, -= ...
▶ 3-Mark Questions & Answers

Q1. What is the ternary operator? Give an example.


The ternary operator (?:) is a shorthand for if-else. Syntax: condition ? expr1 : expr2. Example: int max = (a > b) ?
a : b; – returns a if condition is true, b otherwise.

Q2. Differentiate pre-increment and post-increment.


Pre-increment (++x): variable is incremented first, then used. Post-increment (x++): variable is used first, then
incremented. Example: if x=5, ++x gives 6 immediately; x++ gives 5 first, then x becomes 6.

Q3. What are bitwise operators? Give two examples.


Bitwise operators work on individual bits. & (bitwise AND): 5 & 3 = 1 (0101 & 0011 = 0001). | (bitwise OR): 5 | 3
= 7 (0101 | 0011 = 0111). Used in system-level programming and flag manipulation.
▶ MCQ Questions
No Question Options Answer
.
1. What does the % operator return? a) Quotient b) Remainder
b) Remainder
c) Percentage
d) Exponent
2. What is the result of 10 & 6 in Java? a) 4 c) 2
b) 14
c) 2
d) 6
3. Which operator is used for logical NOT? a) ~ c) !
b) &&
c) !
d) ||
4. What will ++x return if x = 5? a) 5 b) 6
b) 6
c) 4
d) 7
5. Which operator checks object type at runtime? a) typeof b) instanceof
b) instanceof
c) istype
d) ==
5. CONTROL STATEMENTS
▶ 13-Mark Notes
Control statements determine the flow of execution in a Java program. They are classified into three categories.

5.1 Decision-Making Statements


1. if Statement
if (condition) { // execute if true }

2. if-else Statement
if (marks >= 50) { [Link]("Pass"); }
else { [Link]("Fail"); }

3. else-if Ladder
if (marks >= 90) grade = 'A';
else if (marks >= 75) grade = 'B';
else if (marks >= 60) grade = 'C';
else grade = 'F';

4. switch Statement
Selects one of many code blocks to execute based on a value. Works with int, char, String, enum.
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
default: [Link]("Other");
}

5.2 Looping Statements


1. for Loop
for (int i = 1; i <= 5; i++) {
[Link](i);
}

2. while Loop
int i = 1;
while (i <= 5) { [Link](i); i++; }

3. do-while Loop
Executes body at least once, then checks condition.
int i = 1;
do { [Link](i); i++; } while (i <= 5);

4. Enhanced for (for-each) Loop


int[] arr = {1, 2, 3, 4, 5};
for (int x : arr) { [Link](x); }

5.3 Jump Statements


1. break
Exits the current loop or switch immediately.
for (int i=1; i<=10; i++) {
if (i == 5) break; // exits loop when i=5
[Link](i);
}

2. continue
Skips the current iteration and moves to the next.
for (int i=1; i<=5; i++) {
if (i == 3) continue; // skips 3
[Link](i); // prints 1,2,4,5
}

3. return
Exits from the current method and optionally returns a value.
int square(int n) { return n * n; }
▶ 3-Mark Questions & Answers

Q1. Differentiate while and do-while loop.


while loop: entry-controlled; condition is checked first; body may not execute if condition is false initially. do-
while loop: exit-controlled; body executes at least once, then condition is checked.

Q2. What is the difference between break and continue?


break: immediately exits the loop or switch statement. continue: skips the remaining statements in the current
iteration and jumps to the next iteration.

Q3. Write a switch statement to print day name.


switch(n) { case 1: sout("Mon"); break; case 2: sout("Tue"); break; default:
sout("Invalid"); }
▶ MCQ Questions
No Question Options Answer
.
1. Which loop is guaranteed to execute at least once? a) for c) do-while
b) while
c) do-while
d) for-each
2. Which statement skips the current iteration? a) break c) continue
b) return
c) continue
d) exit
3. switch statement in Java can work with which data type? a) float only c) int, char,
b) double only String
c) int, char, String
d) Arrays only
4. What does break do inside a loop? a) Pauses loop b) Ends loop
b) Ends loop entirely
entirely
c) Skips iteration
d) Returns value
5. Which is an entry-controlled loop? a) do-while b) for
b) for
c) Both a and b
d) None
6. CLASSES & OBJECTS
▶ 13-Mark Notes
A class is the fundamental building block of Java. It is a user-defined data type that acts as a blueprint for
creating objects.

6.1 Defining a Class


class ClassName {
// fields (instance variables)
// methods
// constructors
}

class Student {
String name;
int age;
void display() {
[Link](name + " " + age);
}
}

6.2 Creating Objects


An object is an instance of a class. Objects are created using the new keyword.
Student s1 = new Student(); // creates object
[Link] = "Ravi"; // access fields
[Link] = 20;
[Link](); // call method

6.3 The 'this' Keyword


'this' refers to the current object instance. Used to differentiate instance variables from local variables.
class Student {
String name;
Student(String name) {
[Link] = name; // '[Link]' = instance var
}
}

6.4 Methods in Java


Types of Methods
• Instance Methods – Called on an object: [Link]()
• Static Methods – Called on class: [Link]()
• void Methods – Do not return a value
• Return-type Methods – Return a specified type

Method with Parameters and Return


class Calculator {
int add(int a, int b) {
return a + b;
}
}
Calculator c = new Calculator();
int result = [Link](10, 20); // result = 30

6.5 Method Overloading


Defining multiple methods with the same name but different parameters (number, type, or order). Resolved at
compile time.
class Math {
int add(int a, int b) { return a+b; }
double add(double a, double b) { return a+b; }
int add(int a, int b, int c) { return a+b+c; }
}
▶ 3-Mark Questions & Answers

Q1. What is a class? How is an object created?


A class is a user-defined blueprint that defines fields and methods. An object is an instance of a class created
using 'new' keyword. Example: Student s = new Student(); creates object 's' of class Student.

Q2. What is the purpose of 'this' keyword?


'this' refers to the current object. It is used to: (1) Differentiate between instance and local variables with same
name. (2) Call another constructor of the same class: this(). (3) Pass current object as argument: method(this).

Q3. What is method overloading?


Method overloading allows multiple methods with the same name but different parameter lists. The compiler
differentiates them by number/type of arguments. It is compile-time polymorphism. Example: add(int,int) and
add(double,double).
▶ MCQ Questions
No Question Options Answer
.
1. Which keyword is used to create an object in Java? a) create c) new
b) object
c) new
d) class
2. What does 'this' keyword refer to? a) Parent class b) Current
b) Current object object
c) Static method
d) Interface
3. Method overloading is resolved at? a) Runtime b) Compile time
b) Compile time
c) Link time
d) Load time
4. Which is NOT a valid method overloading? a) Different param c) Different
types return type
b) Different param only
count
c) Different return
type only
d) Different param
order
5. What is the return type of a method that returns nothing? a) null c) void
b) int
c) void
d) empty
7. CONSTRUCTORS
▶ 13-Mark Notes
A constructor is a special method used to initialize an object when it is created. It has the same name as the
class and has no return type.

7.1 Properties of Constructors


• Same name as the class
• No return type (not even void)
• Automatically called when object is created using new
• Can be overloaded (multiple constructors with different parameters)

7.2 Types of Constructors


1. Default Constructor
If no constructor is defined, Java provides a default no-argument constructor that initializes variables to default
values.
class Box {
int length;
// Java provides default constructor automatically
}
Box b = new Box(); // calls default constructor

2. No-Argument Constructor
User-defined constructor with no parameters. Used to set initial values.
class Box {
int length;
Box() { // no-arg constructor
length = 10;
}
}

3. Parameterized Constructor
Constructor that accepts parameters to initialize fields with custom values.
class Box {
int l, w, h;
Box(int l, int w, int h) {
this.l = l; this.w = w; this.h = h;
}
}
Box b = new Box(5, 3, 2); // parameterized call

7.3 Constructor Overloading


Multiple constructors with different parameter lists in the same class.
class Student {
String name; int age;
Student() { name="Unknown"; age=0; }
Student(String n) { name=n; age=0; }
Student(String n, int a) { name=n; age=a; }
}

7.4 Copy Constructor


A constructor that creates a new object as a copy of an existing object.
class Point {
int x, y;
Point(int x, int y) { this.x=x; this.y=y; }
Point(Point p) { this.x=p.x; this.y=p.y; } // copy
}
Point p1 = new Point(3, 4);
Point p2 = new Point(p1); // copy of p1

7.5 this() Constructor Call


One constructor can call another constructor in the same class using this(). Must be the first statement.
class Box {
int l, w, h;
Box() { this(1, 1, 1); } // calls parameterized
Box(int l,int w,int h){this.l=l;this.w=w;this.h=h;}
}
▶ 3-Mark Questions & Answers

Q1. What is a constructor? How is it different from a method?


A constructor is a special block that initializes an object. Differences: (1) Name same as class (method can have
any name). (2) No return type (methods have return types). (3) Called automatically on object creation (methods
called explicitly).

Q2. What is constructor overloading?


Defining multiple constructors in the same class with different parameter lists. Java differentiates them by
number/type of parameters. Example: Box(), Box(int l), Box(int l, int w, int h) – three overloaded constructors.

Q3. What is the use of this() in constructors?


this() is used to call one constructor from another constructor within the same class. It avoids code duplication.
It must be the first statement in the constructor body. Example: Box() { this(1,1,1); } calls the parameterized
constructor.
▶ MCQ Questions
No Question Options Answer
.
1. What is the return type of a constructor? a) void c) No return
b) int type
c) No return type
d) Object
2. When is a constructor called? a) At class loading b) When object
b) When object is is created
created
c) When method is
called
d) Manually
3. Which call is used to invoke another constructor of the same a) super() c) this()
class? b) self()
c) this()
d) new()
4. If no constructor is written, Java provides? a) Parameterized c) Default
constructor constructor
b) Copy constructor
c) Default
constructor
d) No constructor
5. Constructor can be? a) Overloaded only a) Overloaded
b) Overridden only only
c) Both
d) Neither
8. METHOD OVERRIDING
▶ 13-Mark Notes
Method Overriding allows a subclass to provide a specific implementation of a method that is already defined in
its superclass. It is the basis of runtime polymorphism.

8.1 Rules for Method Overriding


• Method name must be the same
• Parameter list must be the same (same signature)
• Return type must be same or covariant (subtype)
• Access modifier must be same or more accessible
• Cannot override static, final, or private methods
• Requires inheritance (IS-A relationship)

8.2 Example of Method Overriding


class Animal {
void sound() {
[Link]("Generic animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Woof Woof");
}
}
Animal a = new Dog(); // runtime polymorphism
[Link](); // prints: Woof Woof

8.3 @Override Annotation


The @Override annotation tells the compiler that the method is intended to override a parent method. If the
signature doesn't match, compiler shows an error. It is a best practice to always use @Override.

8.4 super Keyword in Overriding


The 'super' keyword allows the child class to call the overridden method of the parent class.
class Dog extends Animal {
@Override
void sound() {
[Link](); // calls Animal's sound()
[Link]("Woof Woof");
}
}

8.5 Overriding vs Overloading


Feature Overriding Overloading
Definition Redefine parent method in child Same method, different params
Polymorphism Runtime (Dynamic) Compile-time (Static)
Class Different classes (parent-child) Same class
Signature Must be same Must be different
Return Type Same (or covariant) Can be different
Inheritance Required Not required
▶ 3-Mark Questions & Answers

Q1. What are the rules for method overriding?


Rules: (1) Same method name and parameters. (2) Same or broader access modifier. (3) Same or covariant
return type. (4) Method cannot be private, static, or final. (5) Must be in parent-child class relationship.
@Override annotation is recommended.

Q2. What is runtime polymorphism? Give an example.


Runtime polymorphism occurs when the method to call is determined at runtime based on the actual object
type, not the reference type. Example: Animal a = new Dog(); [Link](); calls Dog's sound() even though 'a' is of
type Animal.

Q3. How does super keyword help in overriding?


[Link]() calls the overridden parent class method from the child class. Useful when you want to extend
parent behavior, not completely replace it. Example: [Link]() in Dog calls Animal's sound() before adding
Dog's custom behavior.
▶ MCQ Questions
No Question Options Answer
.
1. Which type of polymorphism does method overriding a) Compile-time c) Runtime
represent? b) Static
c) Runtime
d) Link-time
2. Can a final method be overridden? a) Yes b) No
b) No
c) Only in same
package
d) Only with
@Override
3. Which annotation indicates method overriding? a) @Inherit c) @Override
b) @Super
c) @Override
d) @Extend
4. [Link]() is used to call? a) Current class c) Parent class
method overridden
b) Interface method method
c) Parent class
overridden method
d) Static method
5. Overriding requires? a) Same class b) Inheritance
b) Inheritance
c) Interface only
d) Static keyword
9. ACCESS SPECIFIERS
▶ 13-Mark Notes
Access specifiers (access modifiers) control the visibility and accessibility of classes, methods, and variables. Java
provides four access levels.

9.1 Types of Access Specifiers


Modifier Same Class Same Package Subclass Other Package
private ✔ ✘ ✘ ✘
default (no modifier) ✔ ✔ ✘ ✘
protected ✔ ✔ ✔ ✘
public ✔ ✔ ✔ ✔

9.2 private
The most restrictive access level. Private members are accessible only within the same class. Used to implement
encapsulation.
class Person {
private String name; // only accessible in Person
public String getName() { return name; }
}

9.3 default (Package-Private)


If no modifier is specified, the member has default access – accessible within the same package only.
class Example {
int value = 10; // default access
}

9.4 protected
Accessible within the same package and by subclasses in different packages. Commonly used with inheritance.
class Animal {
protected String name;
}
class Dog extends Animal {
void show() { [Link](name); } // valid
}

9.5 public
The least restrictive. Public members are accessible from any class in any package.
public class Hello {
public void greet() {
[Link]("Hello!");
}
}

9.6 Access Specifiers for Classes


• A top-level class can only be public or default
• Inner classes can use all four access modifiers
• Interface members are implicitly public
▶ 3-Mark Questions & Answers

Q1. List the four access specifiers in Java and their scope.
(1) private – same class only. (2) default – same package. (3) protected – same package + subclasses. (4) public –
everywhere. The order from most restrictive to least: private < default < protected < public.

Q2. What is the difference between protected and default?


Default access allows access only within the same package. Protected access allows same package access AND
also allows subclasses in different packages to access the member. Protected is broader than default.

Q3. Why is private access used? Give example.


Private access implements encapsulation by hiding data from outside classes. Example: private String password;
in a LoginUser class ensures direct access is prevented; only controlled access via getter/setter methods is
allowed.
▶ MCQ Questions
No Question Options Answer
.
1. Which access modifier is accessible everywhere? a) private d) public
b) protected
c) default
d) public
2. Which modifier allows access within the same package only (no a) private b) default
subclass in other package)? b) default
c) protected
d) public
3. Which modifier is best for encapsulation? a) public c) private
b) default
c) private
d) protected
4. A top-level class in Java can have which modifiers? a) All four c) public or
b) private only default
c) public or default
d) protected only
5. Protected members are accessible in? a) Same class only c) Same
b) Same package package +
only subclasses
c) Same package +
subclasses
d) Everywhere
10. STATIC MEMBERS
▶ 13-Mark Notes
The static keyword in Java is used to define class-level members (variables and methods) that belong to the class
rather than to any specific object. Static members are shared among all objects of a class.

10.1 Static Variables


A static variable (class variable) is shared across all instances of the class. It is initialized only once, when the
class is loaded.
class Counter {
static int count = 0; // shared by all objects
Counter() { count++; }
}
Counter c1 = new Counter();
Counter c2 = new Counter();
[Link]([Link]); // 2

10.2 Static Methods


Static methods belong to the class, not to any object. They can be called without creating an object.
• Can access only static variables and call only static methods directly
• Cannot use 'this' or 'super' keywords
• main() method is static – called by JVM without creating object
class MathUtil {
static int square(int n) { return n * n; }
}
[Link]([Link](5)); // 25

10.3 Static Block


A static block is executed once when the class is loaded, before any objects are created or static methods are
called. Used for static initialization.
class Config {
static String dbUrl;
static {
dbUrl = "jdbc:mysql://localhost/db"; // init
[Link]("Static block executed");
}
}

10.4 Static Nested Class


A static nested class is a nested class that is declared with the static keyword. It can be instantiated without
creating an outer class instance.
class Outer {
static class Inner {
void show() { [Link]("Static inner"); }
}
}
[Link] obj = new [Link]();
[Link]();
10.5 Static vs Instance Members
Feature Static Member Instance Member
Belongs to Class Object
Memory Allocated once Per object
Access [Link] [Link]
'this' keyword Cannot use Can use
Usage Shared state, utilities Object-specific state
▶ 3-Mark Questions & Answers

Q1. What is a static variable? How is it different from instance variable?


Static variable is shared by all objects of a class; allocated once in class memory. Instance variable is unique to
each object; created when object is created. Static: [Link]; Instance: [Link].

Q2. What is a static block? When is it executed?


A static block is executed once when the class is loaded into memory, before object creation. Used for complex
static initialization. Syntax: static { // initialization code }. Multiple static blocks execute in order of appearance.

Q3. Can a static method access instance variables? Why?


No. Static methods cannot access instance variables because they belong to the class, not to any specific object.
Instance variables require an object reference (this), which is not available in static context.
▶ MCQ Questions
No Question Options Answer
.
1. Static variables are shared among? a) Same method b) All objects of
b) All objects of class
class
c) Current object
only
d) Same package
2. When is a static block executed? a) When method c) When class is
called loaded
b) When object
created
c) When class is
loaded
d) At program end
3. Can a static method use 'this' keyword? a) Yes b) No
b) No
c) Only in
constructors
d) Yes, if object
exists
4. How is a static method called? a) [Link]() c)
b) [Link]() [Link]
c) hod()
[Link](
)
d) [Link]()
5. The main() method is static because? a) It is first method b) JVM calls
b) JVM calls without without object
object
c) It uses String[]
d) It is in every class
11. INHERITANCE
▶ 13-Mark Notes
Inheritance is an OOP mechanism where a new class (subclass/child) acquires properties and methods of an
existing class (superclass/parent). It promotes code reuse and establishes an IS-A relationship.

11.1 Syntax
class SubClass extends SuperClass {
// additional fields and methods
}

11.2 Types of Inheritance in Java


1. Single Inheritance
One child class inherits from one parent class.
class Animal { void eat() { sout("eating"); } }
class Dog extends Animal { void bark() { sout("woof"); } }

2. Multilevel Inheritance
A chain of classes: A → B → C. Each class extends the previous.
class A { void methodA() { } }
class B extends A { void methodB() { } }
class C extends B { void methodC() { } }
// C inherits from both A and B

3. Hierarchical Inheritance
Multiple child classes inherit from one parent class.
class Shape { void draw() { } }
class Circle extends Shape { }
class Rectangle extends Shape { }

4. Multiple Inheritance (through Interfaces)


Java does NOT support multiple inheritance through classes to avoid the diamond problem. However, it is
achieved through interfaces.
interface A { void show(); }
interface B { void display(); }
class C implements A, B {
public void show() { }
public void display() { }
}

11.3 super Keyword


The 'super' keyword refers to the parent class. It is used to:
• Access parent class variables: [Link]
• Call parent class method: [Link]()
• Call parent class constructor: super() – must be first line in child constructor
class Animal {
String type = "Animal";
Animal(String t) { [Link] = t; }
}
class Dog extends Animal {
Dog() { super("Dog"); } // calls Animal(String)
void show() { [Link]([Link]); }
}

11.4 Method Overriding in Inheritance


When a subclass provides its own implementation of an inherited method, it is called method overriding. This
enables runtime polymorphism.
class Animal { void sound() { sout("..."); } }
class Cat extends Animal {
@Override void sound() { sout("Meow"); }
}

11.5 final Keyword with Inheritance


• final class – Cannot be inherited: final class String { }
• final method – Cannot be overridden in subclass
• final variable – Acts as a constant; value cannot be changed

11.6 Object Class – Root of Hierarchy


In Java, every class implicitly extends the [Link] class. Object class provides important methods:
• toString() – Returns string representation of object
• equals(Object o) – Compares objects for equality
• hashCode() – Returns hash code of object
• getClass() – Returns runtime class of object
• clone() – Creates copy of object
▶ 3-Mark Questions & Answers

Q1. What is inheritance? List its types in Java.


Inheritance allows a subclass to acquire properties of a superclass using extends keyword. Types: (1) Single –
one parent, one child. (2) Multilevel – chain of classes. (3) Hierarchical – multiple children, one parent. (4)
Multiple – via interfaces only.

Q2. Why doesn't Java support multiple inheritance through classes?


Java avoids multiple inheritance through classes to prevent the Diamond Problem: if two parent classes have the
same method and a child inherits both, ambiguity arises about which method to use. Java solves this using
interfaces with default methods.

Q3. What is the role of 'super' keyword in inheritance?


'super' refers to the parent class. Uses: (1) super() – calls parent constructor (must be first line). (2)
[Link]() – calls parent's overridden method. (3) [Link] – accesses parent class variable when child
has same name variable.
▶ MCQ Questions
No Question Options Answer
.
1. Which keyword is used for inheritance in Java? a) implements c) extends
b) inherit
c) extends
d) derive
2. Which type of inheritance is NOT supported through classes in a) Single d) Multiple
Java? b) Multilevel
c) Hierarchical
d) Multiple
3. Which class is the superclass of all Java classes? a) Main c) Object
b) Super
c) Object
d) Base
4. super() in constructor calls? a) Current c) Parent class
constructor constructor
b) Static block
c) Parent class
constructor
d) Interface method
5. A final class in Java? a) Cannot be a) Cannot be
inherited inherited
b) Cannot have
methods
c) Cannot create
objects
d) Must be abstract
QUICK REVISION – ALL TOPICS AT A GLANCE
Topic Key Concept Key Keyword
1. OOP Principles Encapsulation, Abstraction, Inheritance, Polymorphism class, extends, implements

2. JDK JDK > JRE > JVM; Compile & Run javac, java, bytecode

3. Data Types 8 primitives + reference types; arrays int, char, boolean, new

4. Operators Arithmetic, Logical, Relational, Bitwise, Ternary +, &&, ?:, instanceof

5. Control Stmts if-else, switch, for, while, do-while, break, continue if, switch, for, break

6. Classes & Objects Blueprint + Instance; overloading; this class, new, this, void

7. Constructors Special init method; overloading; this() Constructor, this(), super()

8. Method Overriding Subclass redefines parent method; @Override; super @Override, super, extends

9. Access Specifiers private < default < protected < public private, protected, public

10. Static Members Class-level; shared; static block static, [Link]

11. Inheritance IS-A; types; super; final; Object class extends, super, final

Prepared with reference to: Herbert Schildt & Danny Coward – Java: The Complete Reference, 13th Edition, McGraw Hill, 2024

You might also like