I’ll provide an in-depth explanation of all these Object-Oriented Programming
concepts in Java.
## Final Keyword
The `final` keyword in Java can be applied to variables, methods, and
classes:
- **Final Variables**: Cannot be reassigned after initialization
```java
Final int MAX_VALUE = 100; // Cannot be changed
```
- **Final Methods**: Cannot be overridden by subclasses
```java
Public final void displayInfo() { /* code */ }
```
- **Final Classes**: Cannot be extended/inherited
```java
Public final class ImmutableClass { /* code */ }
```
## Static Keyword
The `static` keyword creates class-level members rather than instance-level:
- **Static Variables**: Shared across all instances of a class
- **Static Methods**: Can be called without creating an object
- **Static Blocks**: Execute when class is loaded into memory
- **Static Classes**: Can only be nested classes (inner classes)
```java
Public class Counter {
Static int count = 0; // Shared across all instances
Public Counter() {
Count++; // Increments the shared counter
Public static void displayCount() {
System.out.println(“Count: “ + count);
```
## Dynamic Binding
Also known as late binding, it’s the process of determining the method to
invoke at runtime rather than compile time. In Java, all method calls to
objects are resolved during runtime.
```java
Class Animal {
Void makeSound() {
System.out.println(“Animal sound”);
Class Dog extends Animal {
@Override
Void makeSound() {
System.out.println(“Bark”);
Public class Main {
Public static void main(String[] args) {
Animal animal = new Dog(); // Reference is Animal, object is Dog
Animal.makeSound(); // Calls Dog’s makeSound() – resolved at runtime
```
## Compile-time Polymorphism
Also called static polymorphism or method overloading, this occurs when
multiple methods with the same name but different parameters exist in a
class.
```java
Class Calculator {
// Method overloading examples
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;
```
## Runtime Polymorphism
Also called dynamic polymorphism or method overriding, this occurs when a
subclass provides a specific implementation of a method that’s already
defined in its parent class.
```java
Class Shape {
Void draw() {
System.out.println(“Drawing a shape”);
Class Circle extends Shape {
@Override
Void draw() {
System.out.println(“Drawing a circle”);
}
Class Rectangle extends Shape {
@Override
Void draw() {
System.out.println(“Drawing a rectangle”);
```
## Inheritance
Inheritance is a mechanism where a new class inherits properties and
behaviors from an existing class:
- **Single Inheritance**: A class inherits from only one class
- **Multilevel Inheritance**: A class inherits from a child class
- **Hierarchical Inheritance**: Multiple classes inherit from one class
- Java doesn’t support multiple inheritance with classes (but does with
interfaces)
```java
// Single inheritance
Class Vehicle {
Void start() {
System.out.println(“Vehicle starting”);
Class Car extends Vehicle {
Void accelerate() {
System.out.println(“Car accelerating”);
// Multilevel inheritance
Class SportsCar extends Car {
Void turboBoost() {
System.out.println(“Sports car boosting”);
```
## Abstract Class
An abstract class cannot be instantiated and may contain abstract methods
(methods without implementation). Abstract classes are designed to be
extended by concrete subclasses.
```java
Abstract class Animal {
// Regular method with implementation
Void eat() {
System.out.println(“The animal eats food”);
// Abstract method – no implementation
Abstract void makeSound();
}
Class Dog extends Animal {
// Must implement all abstract methods
@Override
Void makeSound() {
System.out.println(“The dog barks”);
```
## Interface
An interface is a completely abstract type that contains only method
signatures and constants. All methods are implicitly `public` and `abstract`.
```java
Interface Drawable {
Void draw(); // Abstract by default
// Default method (Java 8+)
Default void displayInfo() {
System.out.println(“Drawing object”);
// Static method (Java 8+)
Static void commonMethod() {
System.out.println(“Common drawing method”);
}
}
Class Circle implements Drawable {
@Override
Public void draw() {
System.out.println(“Drawing a circle”);
```
## Abstract Class vs Interface
| Feature | Abstract Class | Interface |
| Instantiation | Cannot be instantiated | Cannot be instantiated |
| Methods | Can have abstract and concrete methods | All methods are
abstract by default (Java 8+ allows default and static methods) |
| Variables | Can have non-final variables | All variables are final and static by
default |
| Constructor | Can have constructors | Cannot have constructors |
| Access Modifiers | Can use all access modifiers | All methods are implicitly
public |
| Inheritance | Supports single inheritance | A class can implement multiple
interfaces |
| Purpose | When there’s a IS-A relationship | When there’s a HAS-A capability
relationship |
## Access Modifiers
Java has four access modifiers:
1. **Private**: Accessible only within the declared class
2. **Default (Package-Private)**: Accessible within the same package (no
explicit modifier)
3. **Protected**: Accessible within the same package and subclasses
4. **Public**: Accessible from anywhere
```java
Public class AccessDemo {
Private int privateVar; // Only within this class
Int defaultVar; // Within this package
Protected int protectedVar; // Within this package and subclasses
Public int publicVar; // Everywhere
```
**Default vs Protected**:
- Default: Accessible only in the same package
- Protected: Accessible in the same package AND in subclasses (even in
different packages)
## JVM vs JRE vs JDK
**JVM (Java Virtual Machine)**:
- Executes Java bytecode
- Platform-dependent (different implementations for different operating
systems)
- Core responsibilities: Loading, verifying, executing code and providing
runtime environment
**JRE (Java Runtime Environment)**:
- Contains JVM plus libraries and other components needed to run Java
applications
- End users only need JRE to run Java applications
**JDK (Java Development Kit)**:
- Contains JRE plus development tools (compiler, debugger, etc.)
- Required for Java development
## Characteristics of OOP
1. **Encapsulation**: Bundling data (attributes) and methods that
operate on the data into a single unit (class) and restricting direct
access to some of the object’s components
```java
Public class Person {
Private String name; // Encapsulated data
// Getter and Setter methods
Public String getName() { return name; }
Public void setName(String name) { this.name = name; }
```
2. **Inheritance**: Mechanism where a class inherits properties and
behaviors from another class
```java
Class Vehicle { /* code */ }
Class Car extends Vehicle { /* code */ }
```
3. **Polymorphism**: Ability of different objects to respond to the same
method call in different ways
```java
Class Animal { void makeSound() { /* code */ } }
Class Dog extends Animal { void makeSound() { /* code */ } }
Class Cat extends Animal { void makeSound() { /* code */ } }
```
4. **Abstraction**: Hiding complex implementation details and showing
only necessary features
```java
Abstract class Shape {
Abstract double calculateArea();
```
## Characteristics of Java
1. **Platform Independent**: “Write Once, Run Anywhere” (WORA)
2. **Object-Oriented**: Based on objects rather than just functions and
procedures
3. **Simple**: No pointers, operator overloading, multiple inheritance (via
classes)
4. **Secure**: Runs in JVM sandbox, automatic memory management
5. **Robust**: Strong memory management, exception handling, type
checking
6. **Multithreaded**: Built-in support for concurrent programming
7. **Architecture Neutral**: No implementation-dependent features
8. **Portable**: Same behavior on all platforms
9. **High Performance**: Just-In-Time compiler for efficient execution
10. **Distributed**: Extensive networking capabilities
## Super Keyword
The `super` keyword refers to the parent class objects:
- Access parent class variables
- Invoke parent class methods
- Call parent class constructor
```java
Class Parent {
Int value = 10;
Void display() {
System.out.println(“Parent class method”);
Parent(int value) {
This.value = value;
Class Child extends Parent {
Int value = 20;
Child(int value) {
Super(value); // Call parent constructor
Void display() {
System.out.println(“Child value: “ + value);
System.out.println(“Parent value: “ + super.value); // Access parent
variable
Super.display(); // Call parent method
```
## Wrapper Classes
Wrapper classes provide a way to use primitive data types as objects:
| Primitive Type | Wrapper Class |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
Uses of wrapper classes:
- Collections only store objects, not primitives
- Provide utility methods for conversion and manipulation
- Support null values unlike primitives
```java
// Autoboxing (primitive to wrapper)
Int primitiveInt = 42;
Integer wrapperInt = primitiveInt;
// Unboxing (wrapper to primitive)
Integer wrapperDouble = 3.14;
Double primitiveDouble = wrapperDouble;
```
## Procedural vs OOP
**Procedural Programming**:
- Focuses on procedures/functions that operate on data
- Data and functions are separate entities
- Top-down approach
- Examples: C, Pascal
**Object-Oriented Programming**:
- Focuses on objects that contain data and methods
- Data and methods are bundled together
- Bottom-up approach
- Examples: Java, C++, Python, C#
Key differences:
- OOP provides better code reusability through inheritance
- OOP offers better security through encapsulation
- OOP models real-world entities more effectively
- OOP facilitates easier maintenance and modification
## Conditional Statements
Java supports several conditional statements:
1. **If Statement**:
```java
If (condition) {
// Code executed if condition is true
```
2. **If-Else Statement**:
```java
If (condition) {
// Code executed if condition is true
} else {
// Code executed if condition is false
```
3. **If-Else-If Ladder**:
```java
If (condition1) {
// Code executed if condition1 is true
} else if (condition2) {
// Code executed if condition2 is true
} else {
// Code executed if all conditions are false
```
4. **Switch Statement**:
```java
Switch (expression) {
Case value1:
// Code
Break;
Case value2:
// Code
Break;
Default:
// Code
```
5. **Ternary Operator**:
```java
Result = (condition) ? valueIfTrue : valueIfFalse;
```
## Looping Statements
Java supports several looping constructs:
1. **For Loop**:
```java
For (initialization; condition; update) {
// Code to be repeated
```
2. **Enhanced For Loop (For-Each)**:
```java
For (dataType item : collection) {
// Code to process item
}
```
3. **While Loop**:
```java
While (condition) {
// Code to be repeated
```
4. **Do-While Loop**:
```java
Do {
// Code to be repeated
} while (condition);
```
5. **Loop Control Statements**:
- `break`: Exits the loop completely
- `continue`: Skips the current iteration
- `return`: Exits the method (and loop)
## Arrays
An array is a collection of similar data types stored at contiguous memory
locations.
**Declaration and Initialization**:
```java
// Declaration
Int[] numbers;
// or
Int numbers[];
// Initialization
Numbers = new int[5]; // Creates array of size 5
// Declaration and initialization together
Int[] numbers = new int[5];
Int[] numbers = {1, 2, 3, 4, 5};
```
**Accessing Elements**:
```java
Int firstElement = numbers[0]; // Access first element
Numbers[2] = 10; // Modify third element
```
**Array Properties**:
- Fixed size (cannot be changed after creation)
- Zero-indexed (first element is at index 0)
- Store elements of the same data type
- Length is accessed via `array.length` property
**Multi-dimensional Arrays**:
```java
// 2D array declaration and initialization
Int[][] matrix = new int[3][3];
Int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Accessing elements
Int element = matrix[1][2]; // Access element at row 1, column 2
```
**Array Operations**:
- Iteration using loops
- Searching and sorting
- Passing to methods
- Returning from methods
```java
// Iterating through an array
For (int I = 0; I < numbers.length; i++) {
System.out.println(numbers[i]);
// Enhanced for loop
For (int number : numbers) {
System.out.println(number);
```
These concepts form the foundation of Object-Oriented Programming in Java,
providing a robust framework for creating modular, reusable, and
maintainable code.