Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

oop notes

The document covers key Java programming concepts including Exception Handling, Serialization, Generics, Relationships Between Objects, Abstract and Final Classes, GUI, Inheritance, Data Encapsulation, and Method Overloading. Each section provides definitions, code examples, and practice questions to reinforce understanding. The content is structured to facilitate learning and application of these fundamental programming principles.

Uploaded by

huzaifaaakhalid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

oop notes

The document covers key Java programming concepts including Exception Handling, Serialization, Generics, Relationships Between Objects, Abstract and Final Classes, GUI, Inheritance, Data Encapsulation, and Method Overloading. Each section provides definitions, code examples, and practice questions to reinforce understanding. The content is structured to facilitate learning and application of these fundamental programming principles.

Uploaded by

huzaifaaakhalid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

1.

Exception Handling (Error Management in Java)

 Definition:
An exception is an error that occurs during runtime. Exception handling allows for
managing these errors gracefully.
 Key Components:
o try: Block to test code for errors.
o catch: Handles exceptions thrown in the try block.
o finally: Executes cleanup code, regardless of whether an exception occurred.
o throw: Used to explicitly throw an exception.
o throws: Declares exceptions a method might throw.

 Code Examples:

// Simple try-catch example


try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
java
CopyEdit
// Using finally
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // ArrayIndexOutOfBounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index is out of bounds.");
} finally {
System.out.println("Cleanup actions here.");
}

2. Serialization (Object Persistence)

 Definition:
Serialization is the process of converting an object into a byte stream to save it to a file or
transmit it over a network. Deserialization recreates the object from this stream.
 Steps to Serialize and Deserialize:
o Implement the Serializable interface in the class.
o Use ObjectOutputStream to write the object.
o Use ObjectInputStream to read the object.

 Code Examples:

import java.io.*;

// Serializable class
public class Student implements Serializable {
int id;
String name;

public Student(int id, String name) {


this.id = id;
this.name = name;
}
}

// Serialization
Student student = new Student(1, "John");
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("student.dat"));
out.writeObject(student);
out.close();

// Deserialization
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("student.dat"));
Student s = (Student) in.readObject();
in.close();
System.out.println(s.id + " " + s.name);

3. Generics (Type Safety in Java)

 Definition:
Generics enable types (classes and methods) to operate on objects of various types while
providing compile-time type safety.
 Benefits:
o Compile-time type checking.
o No need for type casting.

 Generic Classes and Methods:

// Generic Class
public class Box<T> {
private T value;

public void set(T value) { this.value = value; }


public T get() { return value; }
}

Box<String> stringBox = new Box<>();


stringBox.set("Hello");
System.out.println(stringBox.get());
java
CopyEdit
// Generic Method
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}

Integer[] intArray = {1, 2, 3};


printArray(intArray);

 Wildcard Examples:

public static void printList(List<?> list) {


for (Object elem : list) {
System.out.println(elem);
}
}

1. Exception Handling (Error Management in Java)

 Simple Try-Catch Example:

public class Main {


public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
}
}

Finally Block Example:

public class Main {


public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // ArrayIndexOutOfBounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds.");
} finally {
System.out.println("Cleanup actions here.");
}
}
}
 Custom Exception Example:

class InvalidAgeException extends Exception {


public InvalidAgeException(String message) {
super(message);
}
}

public class Main {


public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above.");
}
}

public static void main(String[] args) {


try {
validateAge(16);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}

2. Serialization (Object Persistence)

 Serialization Example:

import java.io.*;

public class Main {


public static void main(String[] args) throws IOException {
Student student = new Student(1, "John");

// Serialization
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("student.dat"));
out.writeObject(student);
out.close();

System.out.println("Serialization done.");
}
}

class Student implements Serializable {


int id;
String name;

public Student(int id, String name) {


this.id = id;
this.name = name;
}
}
 Deserialization Example:

import java.io.*;

public class Main {


public static void main(String[] args) throws IOException,
ClassNotFoundException {
// Deserialization
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("student.dat"));
Student student = (Student) in.readObject();
in.close();

System.out.println("Deserialization done.");
System.out.println("ID: " + student.id + ", Name: " +
student.name);
}
}

class Student implements Serializable {


int id;
String name;

public Student(int id, String name) {


this.id = id;
this.name = name;
}
}

3. Generics (Type Safety in Java)

 Generic Class Example:

public class Box<T> {


private T value;

public void set(T value) {


this.value = value;
}

public T get() {
return value;
}

public static void main(String[] args) {


Box<String> stringBox = new Box<>();
stringBox.set("Hello Generics");
System.out.println(stringBox.get());
}
}

 Generic Method Example:

java
CopyEdit
public class Main {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}

public static void main(String[] args) {


Integer[] intArray = {1, 2, 3, 4};
String[] strArray = {"Java", "Generics"};

printArray(intArray);
printArray(strArray);
}
}

 Wildcard Example:

java
CopyEdit
import java.util.ArrayList;
import java.util.List;

public class Main {


public static void printList(List<?> list) {
for (Object elem : list) {
System.out.println(elem);
}
}

public static void main(String[] args) {


List<String> strings = new ArrayList<>();
strings.add("Java");
strings.add("OOP");

printList(strings);
}
}
Practice question
1. Relationships Between Objects

 Definition:
Relationships between objects define how objects interact and
relate to each other.
o Association: A "uses-a" relationship (e.g., a student uses a
library).
o Aggregation: A "has-a" relationship (e.g., a department has
professors).
o Composition: A "part-of" relationship (e.g., a car has an
engine).

class Engine {
void start() {
System.out.println("Engine started.");
}
}

class Car {
private Engine engine = new Engine(); // Composition

void drive() {
engine.start();
System.out.println("Car is driving.");
}
}
public class Main { public static void main(String[] args) {Car car = new
Car();
car.drive();
}
}

 Practice Question:
Implement a class Library that contains multiple Books using aggregation.

Here are short notes, code examples, and practice questions for each topic, simplified for
easier understanding:

1. Relationships Between Objects

 Definition:
Relationships between objects define how objects interact and relate to each other.
o Association: A "uses-a" relationship (e.g., a student uses a library).
o Aggregation: A "has-a" relationship (e.g., a department has professors).
o Composition: A "part-of" relationship (e.g., a car has an engine).

 Code Example:

java
CopyEdit
class Engine {
void start() {
System.out.println("Engine started.");
}
}

class Car {
private Engine engine = new Engine(); // Composition

void drive() {
engine.start();
System.out.println("Car is driving.");
}
}

public class Main {


public static void main(String[] args) {
Car car = new Car();
car.drive();
}
}

 Practice Question:
Implement a class Library that contains multiple Books using aggregation.

2. Abstract and Final Classes

 Abstract Class:
o Cannot be instantiated.
o Used as a base class to provide common functionality for
derived classes.
o Contains abstract methods (no body).

 Final Class:
o Cannot be extended.
o Used to prevent inheritance.

 Practice Question:
Create an abstract class Shape with a method calculateArea().
Extend it to Circle and Rectangle.

Code: abstract class Animal {


abstract void sound(); // Abstract method

}
class Dog extends Animal {

void sound() {

System.out.println("Dog barks.");

final class Cat {

void sound() {

System.out.println("Cat meows.");

public class Main {

public static void main(String[] args) {

Animal dog = new Dog();

dog.sound();

Cat cat = new Cat();

cat.sound();
}

}
3. Introduction to GUI (Graphical User Interface)

 Definition:
GUI allows users to interact with the application using graphical
elements like buttons, text fields, etc.

 Practice Question:
Create a GUI with a text field and a button. When clicked, the
button should display the entered text in a label.

import javax.swing.*;

public class Main {


public static void main(String[] args) {
JFrame frame = new JFrame("Simple GUI");
JButton button = new JButton("Click Me!");

button.setBounds(100, 100, 120, 50);


frame.add(button);

frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
}
}
4. Inheritance

 Definition:
Inheritance allows a class to inherit properties and methods from
another class.
 Practice Question:
Create a class Person with properties name and age. Extend it to
Student with additional property grade.

 Code Example:
class Parent {
void display() {
System.out.println("I am a parent class.");
}
}

class Child extends Parent {


void show() {
System.out.println("I am a child class.");
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child();
child.display();
child.show();
}
}

5. Data Encapsulation and Hiding

 Definition:
Encapsulation hides the internal state of an object and allows
controlled access through getters and setters.
 Practice Question:
Create a class Car with private properties speed and fuel. Use
methods to access and modify them.

 Code Example:
class BankAccount {
private double balance;

public void deposit(double amount) {


balance += amount;
}

public double getBalance() {


return balance;
}
}

public class Main {


public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(500);
System.out.println("Balance: " +
account.getBalance());
}
}

6. Method Overloading

 Definition:
Method overloading allows multiple methods with the same name
but different parameter lists.
 Practice Question:
Create a class Shape with an overloaded method calculateArea()
for circle and rectangle.


 Code Example:
class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

Public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3));
System.out.println(calc.add(2.5, 3.5));
}
}

You might also like