0% found this document useful (0 votes)
20 views31 pages

Composition vs Inheritance in Java OOP

The document discusses Object Oriented Programming concepts, focusing on Composition vs. Inheritance and Exception Handling in Java. It explains the differences between composition and inheritance, the types of exceptions, and the mechanisms for handling exceptions using keywords like try, catch, throw, and throws. Additionally, it includes review questions to reinforce understanding of these concepts.

Uploaded by

enda667788
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)
20 views31 pages

Composition vs Inheritance in Java OOP

The document discusses Object Oriented Programming concepts, focusing on Composition vs. Inheritance and Exception Handling in Java. It explains the differences between composition and inheritance, the types of exceptions, and the mechanisms for handling exceptions using keywords like try, catch, throw, and throws. Additionally, it includes review questions to reinforce understanding of these concepts.

Uploaded by

enda667788
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

Object Oriented Programming

(ECEg3101)

CHAPTER FOUR

COMPOSITION VS. INHERITANCE AND ERROR


HANDLING & EXCEPTIONS
Composition
// Library class contains list of books.
• Composition provides code reusability
class Library {
• We do not extend the class for this.
// reference to refer to the list of books.
• Example private final List<Book> books;
Library(){
// class book
books = new ArrayList<>();
class Book {
}
public String title;
public void add(Book b){
public String author; [Link](b);
Book(String t, String a){ }
[Link] = t; public List<Book> getTotalBooksInLibrary(){

[Link] = a; return books;

} }
}
}
Haramaya University, HiT, ECE Saturday, February 22, 2025 2
Composition…
class Main {
public static void main(String[] args) {
// Creating the Objects of Book class.
Book b1 = new Book("EffectiveJ Java","Joshua Bloch");
Book b2 = new Book("Thinking in Java","Bruce Eckel");
Book b3 = new Book("Java: The Complete Reference","Herbert Schildt");
// Creating the list which contains the no. of books.
Library library = new Library();
[Link](b1); [Link](b2); [Link](b3);
List<Book> bks = [Link]();
for (Book bk : bks) {
[Link]("Title : " + [Link] + " and " + " Author : " + [Link]);
}
}
}
Haramaya University, HiT, ECE Saturday, February 22, 2025 3
Inheritance Vs Composition
Inheritance Composition

• We define the class which we are


• we only define a type which we want to use
inheriting(super class)
• it can change at runtime
• It cannot be changed at runtime

• we can only extend one class • allows to use functionality from different class.

• we are using independent of parent or child


• we need parent class in order to test child class.
class

• Inheritance cannot extend final class. • allows code reuse even from final classes.

• It is an is-a relationship. • it is a has-a relationship.

Haramaya University, HiT, ECE Saturday, February 22, 2025 4


Exception Handling Basics
• Exception is an abnormal condition.
• In java, an exception is an event that disrupts the normal flow of the
program.
• It is an object which is thrown at runtime
• Exception handling
• a mechanism to handle runtime errors such as ClassNotFound, IO,
SQL…

Haramaya University, HiT, ECE Saturday, February 22, 2025 5


Types of Exception
 Bugs or errors that we don't want

 They restrict our program's normal


execution of code

 are referred to as exceptions

• Exceptions are categorized as

1. Checked Exception

2. Unchecked Exception

3. Error

Haramaya University, HiT, ECE Saturday, February 22, 2025 6


Checked Exception

• The classes that directly inherit the Throwable

class are known as checked exceptions.

• For example

• IOException, SQLException, etc.

• They are checked at compile-time.

Haramaya University, HiT, ECE Saturday, February 22, 2025 7


Unchecked Exception
• The classes that inherit the RuntimeException are

known as unchecked exceptions.

• For example

• ArithmeticException, NullPointerException,

ArrayIndexOutOfBoundsException, etc.

• Unchecked exceptions are not checked at

compile-time, but they are checked at runtime.

Haramaya University, HiT, ECE Saturday, February 22, 2025 8


Error

• Error is irrecoverable Error

• Some example of errors are


StackOverflowError
• OutOfMemoryError

• VirtualMachineError VirtualMachineError

• stack overflow etc.


OutOfMemoryError

Haramaya University, HiT, ECE Saturday, February 22, 2025 9


Java Exception class
IOException

SQLException
Exception ArithmeticException
ClassNotFoundException
NullPointerException
Throwable

RuntimeException
NumberFormatException
ArrayIndexOutOfBound
StackOverflowError
Exception
IndexOutOfBoundException
StringOutOfBoundExce
Error VirtualMachineError
ption

OutOfMemoryError

Haramaya University, HiT, ECE Saturday, February 22, 2025 10


Java Exception Vs Error
Can Happen
Possible to Can be Caused by
at Compile Caused by Impossible to Unchecked Happen at
Recover checked or the
time and application Recover Type Runtime
from unchecked Environment
runtime

Exception Error

Exception Vs Error

Haramaya University, HiT, ECE Saturday, February 22, 2025 11


Java Exception Handling Keywords
• The exception handling is one of the powerful mechanism to
handle runtime errors
• There are five keywords used in java exception handling

try catch finally

throw throws

Haramaya University, HiT, ECE Saturday, February 22, 2025 12


Java Exception Handling Keywords…
• Block to place an exception code • Used to catch exception • Used to execute the necessary

• Followed by either catch or finally • Preceded by the try block code of the program

• Can’t use try block alone • Can be followed by finally • Executed whether the exception is

handled or not

try catch Finally

• Used to throw exception • Used to declare exception

• Specify there may occur an exception in the method

• Used with method signature

throw throws

Haramaya University, HiT, ECE Saturday, February 22, 2025 13


try-catch
• try: Allows you to define a block of code to be tested for errors
• catch: allows you to define a block of code to be executed, if an error occurs in the try block
• The try and catch keywords come in pair
• Syntax
try{
// Block of code to try
}
catch (Exception e){
// Block of code to handle error
}

Haramaya University, HiT, ECE Saturday, February 22, 2025 14


try-catch…
• Example 1 (Exception without try-catch)
public class Main {

public static void main(String[] args) {

int[] myNumbers = {1, 2, 3};

[Link](myNumbers[10]); // error!

Exception in thread "main" [Link]: Index

10 out of bounds for length 3 at [Link]([Link])

Haramaya University, HiT, ECE Saturday, February 22, 2025 15


try-catch…
Example 2 (Catching Exception)
Output
public class Main {
public static void main(String[ ] args) { Something went wrong.
try { rest of the code
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
}
catch (Exception e) {
[Link]("Something went wrong.");
}
[Link]("rest of the code.");
}
}

Haramaya University, HiT, ECE Saturday, February 22, 2025 16


try-catch…
Example 3 (Catching ArithmeticException) [Link]("rest of the code...");

public class Main{ }

public static void main(String args[]){ }

try{

int data=100/0; Output

} [Link]: / by zero

catch(ArithmeticException e){ rest of the code...


[Link](e);

Haramaya University, HiT, ECE Saturday, February 22, 2025 17


try-catch…
Example 3 (Catching NullPointerException) [Link]("NullPointerException
occurred ");
public class Main{
[Link]([Link]());
public static void main(String args[]){
}
try{
[Link]("rest of the code...");
String str = null;
}
int l = [Link]();
}
[Link]("length=" + l);
Output
} NullPointerException occurred null
catch(NullPointerException e){ rest of the code...

Haramaya University, HiT, ECE Saturday, February 22, 2025 18


try-catch…
catch (NullPointerException e) {
Example 4 (Catching Multiple Exception)
[Link]("NullPointerException
public class MultipleCatchExample { occurred: " + [Link]());
public static void main(String[] args) { }
try { }
int[] numbers = {1, 2, 3}; }
[Link](numbers[4]);
}
catch (ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBoundsExcep
tion occurred: " + [Link]());
}

Haramaya University, HiT, ECE Saturday, February 22, 2025 19


try-catch…
• Example 5 (multiple try-catch)
public class Main {
public static void main(String[] args) {
try{
int dividend = 10;
int divisor = 0;
int quotient = dividend / divisor;
int remainder = dividend % divisor;
[Link]("Division Result: " + quotient);
[Link]("Remainder: " + remainder);
} catch (ArithmeticException e) {
[Link]("ArithmeticException occurred: " + [Link]());
}
Haramaya University, HiT, ECE Saturday, February 22, 2025 20
try-catch…
[Link]("Length: " + length);
Example 5 (multiple try-catch)…
[Link]("First Character: " +
try { // String Manipulation
firstChar);
String str1 = null;
[Link]("Uppercase: " +
String str2 = "World";
uppercase);
String concatenatedString = str1 + " " + str2;
}
int length = [Link]();
catch (StringIndexOutOfBoundsException e){
char firstChar = [Link](0);
[Link]("Exception occurred: "
String uppercase =
+ [Link]());
[Link]();
}
[Link]("Concatenated String: " +
}
concatenatedString);
}
Haramaya University, HiT, ECE Saturday, February 22, 2025 21
finally
• Used to execute the important code of the
try {
program // Protected code
try { } catch (IOException e1) {
// Protected code // Catch block for IOException
} catch (Exception e1) { } catch (SQLException e2) {
// Catch block for e1 // Catch block for SQLException }
} catch (Exception e2) { finally {
// Catch block for e2 // This block is always executed
} finally { }
// This block is always executed
}

Haramaya University, HiT, ECE Saturday, February 22, 2025 22


finally…
• is always executed whether exception is handled or not
• can be used to put "cleanup" code such as closing a file, closing
connection etc.
class Finally{
public static void main(String args[]){ finally {
try{ [Link]("finally
int data=25/5;
block is always executed");
[Link](data);
} }

catch(ArithmeticException e){ }
[Link](e); }
}
Haramaya University, HiT, ECE Saturday, February 22, 2025 23
throw
• Used to throw an exception.

void a() {

throw new ArithmeticException("Incorrect");

} • Used to throw exception

throw

Haramaya University, HiT, ECE Saturday, February 22, 2025 24


Throw…
• Example: Throw an exception if age is below 18 public static void main(String[] args){
public class Main {
checkAge(15);
static void checkAge(int age) {
}
if (age < 18) {
}
throw new ArithmeticException ("Access
denied - You must be at least 18 years
old.");
} • Used to throw exception

else{
[Link]("Access granted!"); throw
}

}
Haramaya University, HiT, ECE Saturday, February 22, 2025 25
throws
• Used to declare exceptions.
• Gives an information to the programmer that there may occur an exception
• It is better for the programmer to provide the exception handling code
• so that normal flow can be maintained.

• Syntax
return_type method_name() throws exception_class_name{
// meth od code
}

Haramaya University, HiT, ECE Saturday, February 22, 2025 26


throws…
public class Main { public static void main(String[]
static void checkAge(int age) throws args) {
ArithmeticException {
checkAge(15);
if (age < 18) {
}
throw new ArithmeticException("Access
denied - You must be at least 18 years old."); }
}
else {
[Link]("Access granted");
}
}
Haramaya University, HiT, ECE Saturday, February 22, 2025 27
throw vs throws

throw throws

Used to throw an exception for a method Used to indicate what exception type may be
thrown by a method

Cannot throw multiple exceptions Can declare multiple exceptions

Syntax Syntax
• throw is followed by an object (new type) • throws is followed by a class
• used inside the method • and used with the method signature

Haramaya University, HiT, ECE Saturday, February 22, 2025 28


Review Questions
1. What is the difference between composition and inheritance in object-oriented programming?
Provide an example of each.

2. Explain the concept of checked exceptions and unchecked exceptions in Java. How do they
differ in terms of handling?

3. What is the purpose of the finally block in exception handling? Give an example where it
would be useful?

4. Describe the role of the throw keyword in Java. How is it different from the throws keyword?

5. Explain the concept of method overriding in the context of inheritance. How does it differ from
method overloading?

Haramaya University, HiT, ECE Saturday, February 22, 2025 29


Review Questions…
6. An __________ is an event that disrupts the normal flow of the program.

7. The __________ block is used to define a block of code that should be executed regardless of
whether an exception is thrown or not.

8. __________ exceptions are checked at compile-time, while __________ exceptions are


checked at runtime.

9. The __________ keyword is used to explicitly throw an exception in Java.

10. In Java, the __________ class is the superclass of all exceptions and errors, and it provides
methods like getMessage() and printStackTrace() to handle exception details

Haramaya University, HiT, ECE Saturday, February 22, 2025 30


Review Questions…
11. What is the purpose of the try-catch block in Java? Provide a simple example of how it can be
used to handle an ArrayIndexOutOfBoundsException.

12. Explain the difference between throw and throws in Java. Provide a scenario where you
would use each.

13. What will happen if you divide a number by zero in Java without using exception handling?
How can you handle this situation using a try-catch block?

14. What is the role of the finally block in exception handling? Can you give an example where
the finally block would execute even if an exception is not thrown?

Haramaya University, HiT, ECE Saturday, February 22, 2025 31

You might also like