0% found this document useful (0 votes)
5 views72 pages

Java Classes, Objects, and Swing Overview

The document provides an overview of Java programming concepts including classes, objects, methods, access modifiers, and keywords like static and final. It also introduces Swing and AWT for creating graphical user interfaces, detailing components, event handling, and layout managers. Examples and syntax are included to illustrate each concept.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views72 pages

Java Classes, Objects, and Swing Overview

The document provides an overview of Java programming concepts including classes, objects, methods, access modifiers, and keywords like static and final. It also introduces Swing and AWT for creating graphical user interfaces, detailing components, event handling, and layout managers. Examples and syntax are included to illustrate each concept.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# **1.

Class in Java**

### **Theory:**

A **class** is a **blueprint or template** from which objects are created.

It contains **fields (variables)** and **methods (functions)** that define the behavior of an
object.

### **Syntax:**

```java

class ClassName {

// data members

// methods

```

### **Example:**

```java

class Student {

int id;

String name;

void display() {

[Link](id + " " + name);


}

```

---

# **2. Object in Java**

### **Theory:**

An **object** is an **instance of a class**.

It represents a **real-world entity** like a student, car, or employee.

Objects are used to **access data members and methods** of the class.

### **Example:**

```java

public class Main {

public static void main(String[] args) {

Student s1 = new Student(); // create object

[Link] = 101;

[Link] = "Rahul";

[Link](); // Access method

}
```

### **Output:**

```

101 Rahul

```

---

# **3. Methods in Java**

### **Theory:**

A **method** is a block of code that performs a specific task.

It helps in **code reuse and modular programming**.

### **Syntax:**

```java

returnType methodName(parameters) {

// method body

```

### **Example:**
```java

class Calculator {

int add(int a, int b) {

return a + b;

public class Test {

public static void main(String[] args) {

Calculator c = new Calculator();

[Link]("Sum = " + [Link](5, 3));

```

### **Output:**

```

Sum = 8

```

---

# **4. Access Modifiers in Java**


### **Theory:**

Access modifiers define the **scope (visibility)** of a class, method, or variable.

| Modifier | Scope / Accessibility |

| ------------------------- | -------------------------------------------- |

| **public** | Accessible from anywhere |

| **private** | Accessible only within the same class |

| **protected** | Accessible within same package or subclasses |

| **default (no modifier)** | Accessible only within same package |

### **Example:**

```java

class Demo {

public int a = 10;

private int b = 20;

public void show() {

[Link]("a = " + a);

[Link]("b = " + b);

public class Main {

public static void main(String[] args) {


Demo d = new Demo();

[Link](); // works fine

[Link](d.a); // accessible

// [Link](d.b); // Error: b has private access

```

---

# **5. static Keyword in Java**

### **Theory:**

`static` keyword is used for **members (variables, methods, blocks)** that belong to the
**class rather than objects**.

* Static members are **shared by all objects**.

* You can access static members **without creating an object**.

### **Example:**

```java

class Student {

int id;

String name;
static String college = "ABC College"; // shared by all objects

Student(int i, String n) {

id = i;

name = n;

void display() {

[Link](id + " " + name + " " + college);

public class Test {

public static void main(String[] args) {

Student s1 = new Student(1, "Ravi");

Student s2 = new Student(2, "Amit");

[Link]();

[Link]();

```

### **Output:**

```

1 Ravi ABC College


2 Amit ABC College

```

---

# **6. final Keyword in Java**

### **Theory:**

The `final` keyword is used to **restrict modification**.

| Use of `final` | Meaning |

| ------------------ | ---------------------------------- |

| **final variable** | Value cannot be changed (constant) |

| **final method** | Cannot be overridden |

| **final class** | Cannot be inherited |

---

### **Example 1 – final variable:**

```java

class Demo {

final int x = 100; // constant

void show() {

// x = 200; Error: cannot change final variable


[Link](x);

```

### **Example 2 – final method:**

```java

class Parent {

final void display() {

[Link]("Parent method");

class Child extends Parent {

// void display() {} Error: cannot override final method

```

### **Example 3 – final class:**

```java

final class A {

void show() {

[Link]("Final class");

}
}

// class B extends A {} Error: cannot inherit final class

```

---

# **Summary Table**

| Concept | Definition | Example |

| -------------------- | ----------------------------- | -------------------------------- |

| **Class** | Blueprint or template | `class Student { }` |

| **Object** | Instance of class | `Student s = new Student();` |

| **Method** | Block of code performing task | `void display() { }` |

| **Access Modifiers** | Define visibility | `public`, `private`, `protected` |

| **static** | Belongs to class, not object | `static int count;` |

| **final** | Restricts changes | `final int x = 10;` |


# **SWING in Java**

---

## **1. Introduction**

### **What is Swing?**

**Swing** is a part of **Java’s GUI (Graphical User Interface)** toolkit.

It is used to create **window-based desktop applications** — such as forms, menus,


buttons, text fields, etc.

Swing is built on top of **AWT (Abstract Window Toolkit)** but is **more powerful, flexible,
and lightweight**.

---

### **Package:**

```java

import [Link].*;

```

---

### **Key Features of Swing:**


Lightweight components (written in pure Java)

Platform-independent

Supports **pluggable look and feel**

Provides advanced UI controls (like tables, trees, sliders)

Follows MVC (Model-View-Controller) architecture

---

## **2. Swing Class Hierarchy**

The main hierarchy (from top to bottom):

```

Object

↳ Component (AWT)

↳ Container (AWT)

↳ JComponent (Swing)

↳ JLabel

↳ JButton

↳ JTextField

↳ JTextArea

↳ JCheckBox

↳ JComboBox

↳ JTable
↳ JPanel

↳ Window

↳ Frame

↳ JFrame (Swing)

```

All **Swing components** inherit from `JComponent`.

`JFrame` is the top-level window container for Swing applications.

---

## **3. Swing Containers (Panes in Swing)**

Swing GUI is organized into **layers** (called *panes*).

| Pane | Description |

| ---------------- | ------------------------------------------------------------- |

| **Root Pane** | The base container that holds all other panes. |

| **Content Pane** | Holds all visible UI components like buttons, labels, etc. |

| **Layered Pane** | Allows overlapping components (Z-ordering). |

| **Glass Pane** | Transparent layer used for drawing or capturing mouse events. |

Usually, we add components to the **content pane**.

---
### **Example: Adding Components to Content Pane**

```java

JFrame frame = new JFrame("Swing Example");

Container c = [Link]();

[Link](new FlowLayout());

```

---

## **4. Common Swing Components**

Let’s see some important and commonly used Swing components

---

### **(A) JLabel**

Used to **display text or image**, but cannot take user input.

#### **Syntax:**

```java

JLabel label = new JLabel("Welcome to Swing!");

```
---

### **(B) JButton**

Used to create a **button** that performs an action when clicked.

#### **Syntax:**

```java

JButton button = new JButton("Click Me");

```

---

### **(C) JTextField**

Used for **single-line user input** (e.g., name, email).

#### **Syntax:**

```java

JTextField tf = new JTextField(20);

```

---
### **(D) JTextArea**

Used for **multi-line input** (e.g., comments, description).

#### **Syntax:**

```java

JTextArea ta = new JTextArea(5, 20);

```

---

## **5. Small Example Using All Components**

```java

import [Link].*;

import [Link].*;

import [Link].*;

public class SwingExample extends JFrame implements ActionListener {

JTextField tf;

JTextArea ta;

JButton btn;

JLabel lbl;

SwingExample() {
// Frame title

setTitle("Swing Components Example");

// Layout manager

setLayout(new FlowLayout());

// Create components

lbl = new JLabel("Enter your name:");

tf = new JTextField(15);

ta = new JTextArea(5, 20);

btn = new JButton("Submit");

// Add ActionListener to button

[Link](this);

// Add components to frame

add(lbl);

add(tf);

add(btn);

add(new JLabel("Message:"));

add(ta);

// Frame settings

setSize(300, 250);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {

String name = [Link]();

[Link]("Hello, " + name + "!\nWelcome to Java Swing.");

public static void main(String[] args) {

new SwingExample();

```

---

### **Output:**

GUI window with:

* A label “Enter your name”

* A text field

* A button “Submit”

* A text area displaying a welcome message after clicking the button

---
### **Explanation:**

1. `JFrame` → Main window container.

2. `JLabel` → Displays static text.

3. `JTextField` → Takes single-line user input.

4. `JButton` → Performs action on click.

5. `JTextArea` → Displays multi-line message output.

6. Event is handled using `ActionListener`.

---

## **6. Summary Table**

| Component | Description | Example |

| -------------- | -------------------------- | ---------------------- |

| **JLabel** | Displays text/image | `new JLabel("Name:")` |

| **JButton** | Creates a clickable button | `new JButton("OK")` |

| **JTextField** | Single-line text input | `new JTextField(20)` |

| **JTextArea** | Multi-line text input | `new JTextArea(5, 20)` |

| **JFrame** | Main window container | `new JFrame("Title")` |

---

**In short:**

> **Swing** = Lightweight GUI toolkit in Java.


> It uses **components (JLabel, JButton, JTextField, etc.)**,

> organized inside **panes (ContentPane, RootPane)**,

> and displayed within a **JFrame**.


# **AWT in Java: Listeners and Layouts**

---

## **1. Introduction to AWT**

**AWT (Abstract Window Toolkit)** is a part of Java used to create **Graphical User
Interface (GUI)** components such as:

* Buttons

* Labels

* TextFields

* Checkboxes

* Windows, etc.

AWT is found in the package:

```java

import [Link].*;

import [Link].*;

```

---

## **2. AWT Listeners (Event Handling)**


### **What is Event Handling?**

When a user interacts with a GUI component (like clicking a button), an **event** occurs.

Java handles these events using **event listeners**.

An **Event Listener** is an interface that listens for specific types of events.

---

### **Event Handling Mechanism (Steps):**

1. **Event Source** → Component that generates the event (e.g., Button).

2. **Event Object** → Carries information about the event (e.g., `ActionEvent`).

3. **Event Listener** → Interface that receives and handles the event.

---

### **Commonly Used AWT Listener Interfaces**

| Listener Interface | Event Type | Common Method |

| --------------------- | -------------------------- | ------------------------------------- |

| `ActionListener` | Button click | `actionPerformed(ActionEvent e)` |

| `ItemListener` | Checkbox, Choice selection | `itemStateChanged(ItemEvent e)` |

| `MouseListener` | Mouse actions | `mouseClicked`, `mousePressed`, etc. |

| `MouseMotionListener` | Mouse drag/move | `mouseDragged`, `mouseMoved`


|
| `KeyListener` | Keyboard input | `keyPressed`, `keyReleased` |

| `WindowListener` | Window events | `windowClosing`, `windowOpened`, etc. |

| `FocusListener` | Focus gained/lost | `focusGained`, `focusLost` |

---

### **Simple Example – ActionListener**

```java

import [Link].*;

import [Link].*;

class MyFrame extends Frame implements ActionListener {

TextField tf;

Button b;

MyFrame() {

tf = new TextField();

[Link](60, 50, 170, 20);

b = new Button("Click Me");

[Link](100, 120, 80, 30);

// Register listener

[Link](this);

add(b);
add(tf);

setSize(300, 200);

setLayout(null);

setVisible(true);

// handle button click

public void actionPerformed(ActionEvent e) {

[Link]("Button Clicked!");

public static void main(String[] args) {

new MyFrame();

```

---

### **Output:**

When you click the button → Text field shows:

```

Button Clicked!
```

---

### **Explanation:**

* `MyFrame` implements `ActionListener`.

* `addActionListener(this)` links the button to the listener.

* `actionPerformed()` is executed when the button is clicked.

---

## **3. Layout Managers**

### **Definition:**

A **Layout Manager** in AWT controls the **position and size** of components inside a
container (like Frame, Panel).

It automatically arranges components — so you don’t have to manually set bounds for
each.

---

### **Common Layout Managers**


| Layout Manager | Description |

| ----------------- | ----------------------------------------------------------------------- |

| **FlowLayout** | Places components in a row (left to right) |

| **BorderLayout** | Divides the container into 5 regions — North, South, East, West,
Center |

| **GridLayout** | Arranges components in rows and columns (like a grid) |

| **CardLayout** | Stacks components (like cards) — one visible at a time |

| **GridBagLayout** | Most flexible layout (complex arrangements) |

| **Null Layout** | No manager — manual positioning using `setBounds()` |

---

### **Example 1 – FlowLayout**

```java

import [Link].*;

class FlowLayoutExample {

FlowLayoutExample() {

Frame f = new Frame("FlowLayout Example");

[Link](new FlowLayout());

[Link](new Button("Button 1"));

[Link](new Button("Button 2"));

[Link](new Button("Button 3"));


[Link](300, 200);

[Link](true);

public static void main(String[] args) {

new FlowLayoutExample();

```

🖥 **Output:**

Buttons appear **in a row**, automatically centered.

---

### **Example 2 – BorderLayout**

```java

import [Link].*;

class BorderLayoutExample {

BorderLayoutExample() {

Frame f = new Frame("BorderLayout Example");

[Link](new BorderLayout());

[Link](new Button("North"), [Link]);


[Link](new Button("South"), [Link]);

[Link](new Button("East"), [Link]);

[Link](new Button("West"), [Link]);

[Link](new Button("Center"), [Link]);

[Link](300, 200);

[Link](true);

public static void main(String[] args) {

new BorderLayoutExample();

```

🖥 **Output:**

Buttons are arranged in **five regions** — North, South, East, West, Center.

---

### **Example 3 – GridLayout**

```java

import [Link].*;

class GridLayoutExample {
GridLayoutExample() {

Frame f = new Frame("GridLayout Example");

[Link](new GridLayout(2, 3)); // 2 rows, 3 columns

for (int i = 1; i <= 6; i++)

[Link](new Button("Button " + i));

[Link](300, 200);

[Link](true);

public static void main(String[] args) {

new GridLayoutExample();

```

🖥 **Output:**

Buttons are placed in a **2 × 3 grid** layout.

---

## **4. Summary Table**

| Concept | Description |

| ------------------ | -------------------------------------------- |
| **AWT** | Abstract Window Toolkit – used to create GUI |

| **Listener** | Interface that handles user actions (events) |

| **ActionListener** | Handles button click |

| **Layout Manager** | Controls component arrangement |

| **FlowLayout** | Components in a single row |

| **BorderLayout** | Divides container into 5 regions |

| **GridLayout** | Components in grid format |

| **Null Layout** | Manual placement using `setBounds()` |

---

**In short:**

> **Listeners** handle user actions like click or key press.

> **Layouts** control how GUI components are arranged inside a window.
## **1. Introduction to Synchronization**

### **Definition:**

**Synchronization** in Java is a technique that allows only **one thread** to access a


**shared resource** (like a variable, method, or object) at a time.

It helps to **prevent data inconsistency** when multiple threads try to modify the same
data **concurrently**.

---

### **Why Synchronization?**

When two or more threads access a shared object simultaneously, they may **interfere**
with each other, causing **race conditions** or **incorrect results**.

Synchronization ensures that **only one thread executes a synchronized block at a time**.

---

### **Key Points:**

* Used to **control thread access** to critical code.

* Implemented using the **`synchronized`** keyword.

* Only **one thread** can hold the **lock (monitor)** of an object at a time.

* Other threads wait until the lock is released.


---

## **2. Types of Synchronization**

| Type | Description |

| -------------------------- | ---------------------------------------------------------------------- |

| **Synchronized Method** | Entire method is locked — only one thread can execute it at a
time. |

| **Synchronized Block** | Only a portion of the code is synchronized — better


performance. |

| **Static Synchronization** | Used for static methods — lock is on the *class* object, not
instance. |

---

### **Syntax:**

**Synchronized Method:**

```java

synchronized void display() {

// code

```

**Synchronized Block:**
```java

void display() {

synchronized(this) {

// code

```

---

## **3. Inter-thread Communication**

When threads share data, sometimes one thread needs to **wait** for another to
complete a task.

For this, Java provides **three methods** from the `Object` class:

`wait()`

`notify()`

`notifyAll()`

These methods are used **inside synchronized blocks** for **communication between
threads**.

---

### **a) wait()**


* Causes the **current thread to wait** until another thread invokes `notify()` or
`notifyAll()`.

* The thread **releases the lock** while waiting.

**Syntax:**

```java

wait();

```

---

### **b) notify()**

* Wakes up **one thread** that is waiting on the same object’s monitor.

**Syntax:**

```java

notify();

```

---

### **c) notifyAll()**


* Wakes up **all threads** that are waiting on the same object’s monitor.

**Syntax:**

```java

notifyAll();

```

---

### **Important Rules:**

* These methods must be called **inside a synchronized block or method**.

* Otherwise, Java throws **`IllegalMonitorStateException`**.

* `wait()` temporarily **releases the lock**, while `notify()` and `notifyAll()` **don’t
release** the lock immediately.

---

## **4. Small Example**

Let’s understand this with a **simple producer-consumer type example**

```java

class Message {

private String msg;


private boolean hasMessage = false;

public synchronized void write(String message) {

while (hasMessage) { // wait if message already exists

try { wait(); } catch (InterruptedException e) {}

msg = message;

hasMessage = true;

[Link]("Written: " + msg);

notify(); // notify reader thread

public synchronized void read() {

while (!hasMessage) { // wait if no message

try { wait(); } catch (InterruptedException e) {}

[Link]("Read: " + msg);

hasMessage = false;

notify(); // notify writer thread

public class TestSync {

public static void main(String[] args) {

Message message = new Message();


Thread writer = new Thread(() -> {

String[] msgs = {"Hello", "Java", "Synchronization"};

for (String m : msgs) {

[Link](m);

try { [Link](500); } catch (InterruptedException e) {}

});

Thread reader = new Thread(() -> {

for (int i = 0; i < 3; i++) {

[Link]();

try { [Link](500); } catch (InterruptedException e) {}

});

[Link]();

[Link]();

```

---

### **Output (approximate):**

```
Written: Hello

Read: Hello

Written: Java

Read: Java

Written: Synchronization

Read: Synchronization

```

---

### **Explanation:**

1. **Writer thread** writes a message, then calls `notify()` to wake the reader.

2. **Reader thread** waits using `wait()` until a message is available.

3. Once read, the reader calls `notify()` to wake the writer again.

4. This continues alternately — demonstrating **synchronization + inter-thread


communication**.

---

## **5. Summary Table**

| Concept | Description |

| ------------------------------------- | ------------------------------------------- |

| **Synchronization** | Controls access to shared resources |

| **wait()** | Thread waits (releases lock) until notified |


| **notify()** | Wakes up one waiting thread |

| **notifyAll()** | Wakes up all waiting threads |

| **Lock (monitor)** | Only one thread can hold it at a time |

| **Must be inside synchronized block** | Yes |

---

**In short:**

> **Synchronization** ensures one-thread-at-a-time access to shared resources,

> and **wait() / notify() / notifyAll()** allow threads to **coordinate** with each other.
## **1. Introduction to Multithreading**

### **Definition:**

**Multithreading** in Java means executing **multiple parts of a program (threads)**


**simultaneously** to make efficient use of CPU time.

Each part of a program that runs independently is called a **thread**.

---

### **Key Points:**

* A **thread** is the smallest unit of a process.

* **Multithreading** allows multiple threads to run **concurrently** within a single


program.

* It improves **performance** and **responsiveness**.

* Java provides built-in support for multithreading through the **`[Link]`** class
and **`Runnable` interface**.

---

### **Advantages:**

Better CPU utilization

Faster program execution

Simplifies complex applications


Supports background operations (like autosaving, downloading, etc.)

---

## **2. Thread Creation in Java**

There are **two main ways** to create threads in Java:

---

### **(A) By Extending the Thread Class**

```java

class MyThread extends Thread {

public void run() {

[Link]("Thread is running...");

public class TestThread {

public static void main(String[] args) {

MyThread t1 = new MyThread();

[Link](); // start the thread

```
**Explanation:**

* We extend the `Thread` class.

* Override the `run()` method — this contains the code to execute.

* Call `start()` to run the thread (it internally calls `run()`).

---

### **(B) By Implementing the Runnable Interface**

```java

class MyRunnable implements Runnable {

public void run() {

[Link]("Thread is running using Runnable...");

public class TestRunnable {

public static void main(String[] args) {

Thread t = new Thread(new MyRunnable());

[Link]();

```
**Explanation:**

* Implement `Runnable` interface and define `run()` method.

* Create a `Thread` object and pass the `Runnable` object to it.

* Call `start()` method.

---

## **3. Thread Life Cycle**

A thread in Java passes through **five main states**:

| State | Description |

| ------------------------ | ----------------------------------------------------------------- |

| **1. New** | Thread is created but not started. |

| **2. Runnable** | Thread is ready to run but waiting for CPU. |

| **3. Running** | Thread is executing its `run()` method. |

| **4. Blocked/Waiting** | Thread is waiting (e.g., sleep, I/O, waiting for another thread). |

| **5. Terminated (Dead)** | Thread has finished execution. |

---

### **Diagram of Thread Life Cycle:**

```

New → Runnable → Running → Waiting/Blocked → Terminated


```

---

## **4. Thread Life Cycle Methods**

| Method | Description |

| --------------- | -------------------------------------------------------------- |

| `start()` | Starts the execution of the thread (calls `run()` internally). |

| `run()` | Contains the code to be executed by the thread. |

| `sleep(ms)` | Temporarily pauses the thread for specified milliseconds. |

| `join()` | Waits for another thread to finish before continuing. |

| `yield()` | Pauses current thread and allows others to execute. |

| `isAlive()` | Checks if the thread is still running. |

| `getName()` | Returns the name of the thread. |

| `setPriority()` | Sets thread execution priority (1–10). |

---

## **5. Simple Example:**

```java

class MyThread extends Thread {

public void run() {

for (int i = 1; i <= 3; i++) {

[Link]([Link]().getName() + " - Count: " + i);


try {

[Link](500); // pause for 0.5 second

} catch (InterruptedException e) {

[Link](e);

public class TestMultiThread {

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

[Link]();

[Link]();

```

---

### **Output (order may vary):**

```

Thread-0 - Count: 1
Thread-1 - Count: 1

Thread-0 - Count: 2

Thread-1 - Count: 2

Thread-0 - Count: 3

Thread-1 - Count: 3

```

---

### **Explanation:**

* Two threads (`t1`, `t2`) run **concurrently**.

* `sleep()` pauses each thread briefly, allowing both to share CPU time.

* The output order changes each time due to **parallel execution**.

---

## **6. Summary**

| Concept | Description |

| ------------------ | -------------------------------------------------- |

| **Thread** | A lightweight sub-process executing independently. |

| **Multithreading** | Running multiple threads simultaneously. |

| **Creation** | Using `Thread` class or `Runnable` interface. |

| **Life Cycle** | New → Runnable → Running → Waiting → Terminated |

| **Main Methods** | `start()`, `run()`, `sleep()`, `join()`, `yield()` |


## **Encapsulation in Java**

### **Definition:**

**Encapsulation** is one of the main principles of **Object-Oriented Programming


(OOP)**.

It means **wrapping data (variables)** and **code (methods)** together into a **single
unit** — called a **class**.

It helps **protect data** from unauthorized access and **controls how data is accessed or
modified**.

---

### **Key Points:**

* Achieved by declaring **variables as private**.

* Provides **public getter and setter methods** to access and update private data.

* Ensures **data hiding** (data is not directly accessible outside the class).

* Improves **security**, **maintainability**, and **modularity** of code.

---

### **Simple Example:**

```java

class Student {
// private data member

private String name;

// getter method

public String getName() {

return name;

// setter method

public void setName(String newName) {

name = newName;

public class TestEncapsulation {

public static void main(String[] args) {

Student s = new Student();

[Link]("Harshad"); // setting value

[Link]([Link]()); // getting value

```

---

### **Output:**
```

Harshad

```

---

### **Explanation:**

1. The variable `name` is **private**, so it **cannot** be accessed directly from outside


the class.

2. The **setter** method `setName()` is used to assign value to `name`.

3. The **getter** method `getName()` is used to retrieve the value of `name`.

4. This way, the class controls how its data is accessed — this is **Encapsulation**.

---

### **Benefits of Encapsulation:**

Data hiding — protects data from unwanted changes.

Easy maintenance — you can change internal code without affecting other classes.

Increased security — access can be controlled using getter/setter.

Code reusability and cleaner structure.

---
## **1. Abstract Class and Abstract Method**

### **Definition:**

An **abstract class** in Java is a **class that cannot be instantiated** (you cannot create
objects of it).

It is used to provide a **base for other classes** and can contain both **abstract**
(unimplemented) and **non-abstract** (implemented) methods.

An **abstract method** is a method that **has no body**, only declaration.

It must be **implemented by the subclass**.

---

### **Key Points:**

* Declared using the keyword `abstract`.

* Can have **abstract** and **concrete (normal)** methods.

* Used when we want to **provide a common base** and **force subclasses** to


implement specific behavior.

* Cannot be instantiated directly.

---

### **Syntax:**

```java
abstract class ClassName {

abstract void methodName(); // abstract method

void normalMethod() { // concrete method

// code

```

---

### **Simple Example:**

```java

abstract class Animal {

abstract void sound(); // abstract method

class Dog extends Animal {

void sound() {

[Link]("Dog barks");

public class TestAbstract {

public static void main(String[] args) {

Animal a = new Dog(); // upcasting


[Link](); // calls Dog's implementation

```

**Output:**

```

Dog barks

```

---

### **Explanation:**

* `Animal` is an abstract class having an abstract method `sound()`.

* `Dog` class extends `Animal` and provides its own implementation.

* `Animal a = new Dog();` demonstrates **runtime polymorphism**.

---

## **2. Interface in Java**

### **Definition:**
An **interface** in Java is a **completely abstract** class used to define a **contract**
(set of methods) that implementing classes must follow.

It contains **abstract methods** (by default) and **constants**.

From **Java 8**, interfaces can also have **default** and **static** methods.

---

### **Key Points:**

* Declared using the keyword `interface`.

* All methods are **public** and **abstract** by default.

* A class implements an interface using the keyword `implements`.

* Supports **multiple inheritance** (a class can implement many interfaces).

---

### **Syntax:**

```java

interface InterfaceName {

void method1();

```

---
### **Simple Example:**

```java

interface Animal {

void sound(); // abstract method

class Cat implements Animal {

public void sound() {

[Link]("Cat meows");

public class TestInterface {

public static void main(String[] args) {

Animal a = new Cat();

[Link]();

```

**Output:**

```

Cat meows
```

---

### **Explanation:**

* `Animal` is an interface declaring method `sound()`.

* `Cat` implements `Animal` and defines its own version of `sound()`.

* We use the **reference of the interface** to call the method — shows polymorphism.

---

## **Difference between Abstract Class and Interface**

| Feature | Abstract Class | Interface |

| --------------- | ---------------------------------------- | ------------------------------------------------------


-------------------- |

| Keyword | `abstract` | `interface` |

| Methods | Can have abstract + non-abstract methods | Only abstract methods (till
Java 7); can have default/static (from Java 8) |

| Variables | Can have instance variables | Only public static final (constants)
|

| Inheritance | Single inheritance only | Multiple inheritance allowed


|

| Object creation | Cannot create object | Cannot create object


|

| Implementation | Subclass uses `extends` | Class uses `implements`


|
# **Static Polymorphism in Java**

---

## **Introduction**

**Polymorphism** is one of the key principles of **Object-Oriented Programming (OOP)**


in Java.

The word **Polymorphism** means *“many forms”* — it allows the same method name to
perform different actions based on the object or parameters.

There are two types of polymorphism in Java:

1. **Compile-time polymorphism** → **Static Polymorphism**

2. **Runtime polymorphism** → **Dynamic Polymorphism**

---

## **Theory of Static Polymorphism**

**Static Polymorphism**, also known as **Compile-Time Polymorphism**, occurs when a


method call is resolved **at compile time** (not at runtime).

It is achieved through **Method Overloading**.

---
### **Method Overloading**

**Method Overloading** means **multiple methods** in the same class having the
**same name** but **different parameters** (number or type).

It allows a class to perform **different tasks** using the **same method name** —
depending on the **arguments passed**.

---

### **Key Points**

* Achieved using **method overloading**.

* Occurs **within the same class**.

* The **compiler** determines which method to call (based on arguments).

* It increases **code readability** and **reusability**.

---

## **Syntax**

```java

class ClassName {

void display(int a) {

[Link]("Method with one int parameter: " + a);

}
void display(int a, int b) {

[Link]("Method with two int parameters: " + a + ", " + b);

```

---

## **Example**

```java

class Calculator {

// Overloaded methods

int add(int a, int b) {

return a + b;

int add(int a, int b, int c) {

return a + b + c;

double add(double a, double b) {

return a + b;

}
public class TestStaticPolymorphism {

public static void main(String[] args) {

Calculator c = new Calculator();

[Link]("Sum of 2 int: " + [Link](5, 10));

[Link]("Sum of 3 int: " + [Link](5, 10, 15));

[Link]("Sum of 2 double: " + [Link](5.5, 2.5));

```

---

## **Output**

```

Sum of 2 int: 15

Sum of 3 int: 30

Sum of 2 double: 8.0

```

---

## **Explanation**
1. The class `Calculator` defines **three versions** of the `add()` method.

2. All methods have the **same name** but **different parameters**.

3. The **compiler** checks the method signature and decides **which method to
execute** at compile time.

4. Hence, this is called **Compile-Time (Static) Polymorphism**.

---

## **Why It’s Called Static**

Because the **method binding** (deciding which method to call) happens **at compile
time**, before the program runs.

---

## **Real-Life Example**

Imagine a **Print** function that can print **different types of data**:

```java

class Printer {

void print(String msg) {

[Link]("Printing string: " + msg);

void print(int num) {

[Link]("Printing number: " + num);


}

void print(double value) {

[Link]("Printing decimal: " + value);

public class TestPrinter {

public static void main(String[] args) {

Printer p = new Printer();

[Link]("Hello");

[Link](123);

[Link](45.67);

```

**Output:**

```

Printing string: Hello

Printing number: 123

Printing decimal: 45.67

```

Here,
The **same method name (`print`)** behaves **differently** depending on the argument
type —

That’s **Static Polymorphism**.

---

## **Comparison: Static vs Dynamic Polymorphism**

| **Aspect** | **Static Polymorphism** | **Dynamic Polymorphism** |

| ---------------------- | -------------------------------------- | ----------------------------------- |

| **Type** | Compile-Time | Runtime |

| **Achieved By** | Method Overloading | Method Overriding |

| **Decision Made** | At Compile Time | At Runtime |

| **Inheritance Needed** | No | Yes |

| **Keyword Used** | Same method name, different parameters | `@Override` (same


method signature) |

| **Example** | Multiple `add()` methods | Parent `show()` overridden in Child


|

| **Who Decides?** | Compiler | JVM |

---

## **Conclusion**

**Static Polymorphism** in Java allows methods with the same name to perform different
tasks, depending on their parameter list.

It makes the code **simpler**, **clearer**, and **easier to maintain**.


# **Package in Java (Detailed Theory)**

---

## **Definition**

A **package** in Java is a **collection of related classes, interfaces, and sub-packages**


that are grouped together to provide **modularity**, **reusability**, and **organized
structure** in large programs.

It acts as a **namespace** that helps to **avoid naming conflicts** and makes it easier to
locate and use classes.

In simple terms, a package in Java is like a **folder** in a computer that contains related
files.

---

## **Purpose of Using Packages**

When a Java program grows in size, it may contain hundreds of classes.

To manage them easily, Java provides packages that help in organizing the classes into
meaningful groups.

---

## **Advantages of Packages**
1. **Reusability:**

Classes written once inside a package can be reused in other programs by importing the
package.

2. **Avoiding Name Conflicts:**

Packages provide a unique namespace.

For example, `[Link]` and `[Link]` are two different classes with the same
name but in different packages.

3. **Access Control:**

Packages help control access using access modifiers (`public`, `protected`, `private`,
and default).

4. **Modularity:**

Packages divide the project into small modules that are easy to maintain and update.

5. **Ease of Maintenance:**

Since related classes are grouped together, maintaining and debugging the code
becomes simpler.

---

## **Types of Packages**

### 1. **Built-in Packages**


These are predefined packages provided by Java API.

Some commonly used built-in packages are:

| Package Name | Description |

| ------------ | -------------------------------------------------------------- |

| `[Link]` | Contains fundamental classes (String, Math, System, Object). |

| `[Link]` | Contains utility classes like collections, Date, Scanner, etc. |

| `[Link]` | Contains classes for input and output (File, BufferedReader). |

| `[Link]` | Provides classes for database programming using JDBC. |

| `[Link]` | Contains classes for networking (Socket, URL). |

---

### 2. **User-defined Packages**

These are created by programmers to group their own classes and interfaces.

---

## **Creating a User-defined Package**

You can create a package by using the **`package`** keyword at the **top** of the Java
source file.

### **Syntax:**
```java

package packagename;

```

### **Example:**

```java

package mypackage;

public class Example {

public void show() {

[Link]("This is a user-defined package example.");

```

**Steps to Create a Package:**

1. Write the class and declare the package name using the `package` keyword.

2. Save the file with the same class name (e.g., `[Link]`).

3. Compile using the `javac` command with `-d` option:

```bash

javac -d . [Link]

```
The `-d .` option creates the directory structure automatically.

Example folder structure:

```

mypackage/

[Link]

```

---

## **Accessing a User-defined Package**

To use the classes from a package in another program, you must import them using the
**`import`** statement.

### **Syntax:**

```java

import [Link];

```

or

```java

import packagename.*;

```
### **Example:**

**File 1: ([Link])**

```java

package mypackage;

public class Message {

public void display() {

[Link]("Hello from user-defined package!");

```

**File 2: ([Link])**

```java

import [Link];

public class Test {

public static void main(String[] args) {

Message m = new Message();

[Link]();

}
```

### **Output:**

```

Hello from user-defined package!

```

---

## **Ways to Access a Package**

1. **Using fully qualified name**

```java

[Link] m = new [Link]();

[Link]();

```

(No need for `import` statement)

2. **Using `import [Link];`**

Imports only the specified class.

3. **Using `import packagename.*;`**

Imports all classes from the package.


---

## **Sub-Packages**

A package can also contain **sub-packages**.

For example:

```

package [Link];

```

Here, `students` is a sub-package inside the main package `college`.

Folder structure:

```

college/

students/

[Link]

```

---

## **Access Modifiers and Packages**


| Modifier | Accessible within Same Package | Accessible from Other Package (through
inheritance) | Accessible from Other Package (non-subclass) |

| ----------- | ------------------------------ | --------------------------------------------------- | ---------------


----------------------------- |

| `public` | | | |

| `protected` | | | |

| (default) | | | |

| `private` | | | |

---

## **Conclusion**

A **package** in Java is an essential feature for organizing and structuring large programs.

It helps developers to:

* Avoid name conflicts

* Reuse existing code

* Control access

* Maintain modularity and readability

By using built-in and user-defined packages, Java applications become **well-


structured**, **efficient**, and **easy to manage**.

---.

You might also like