Module1.4_Inheritance_Packages_Exceptions
Module1.4_Inheritance_Packages_Exceptions
Amar Jukuntla,
Assistant Professor, ACSE,
VFSTR University
Index
• Introduction to inheritance
• Method overriding
• Usage of final keyword
• Abstract Classes
• Interfaces
• Access Control
• Packages
• Exception handling
• References
Sub Class
B C D
B C
SubClass
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Method overriding
• If subclass (child class) has the same method as declared in
the parent class, it is known as method overriding in Java.
• In other words, If a subclass provides the specific implementation of
the method that has been declared by one of its parent class, it is
known as method overriding.
• Method overriding is used for runtime polymorphism
Can have abstract methods: These methods do not have a body and
must be implemented by subclasses.
Can have concrete methods: These methods have a body and provide a
default implementation.
Can have fields and constructors: Like regular classes, abstract classes
can have fields and constructors, though constructors are called only through subclass
instantiation.
// Regular method
public void sleep() {
System.out.println("The animal is sleeping");
}
}
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Exception
"thrown" here
Thrown exception matched against first
set of exception handlers
Exception
handler
If it fails to match, it is matched against
next set of handlers, etc.
Exception
handler
try {
// Code that might throw an exception
int data = 50 / 0;
// This will throw ArithmeticException
}
catch (ArithmeticException e) {
// Code to handle the ArithmeticException
System.out.println("Cannot divide by zero");
}
finally {
// Code that will execute regardless of an exception
System.out.println("Finally block is always executed");
}
Usage Type of exception Using throw keyword, we can Using throws keyword, we can declare both
only propagate unchecked exception i.e., the checked and unchecked exceptions. However, the
checked exception cannot be propagated using throws keyword can be used to propagate checked
throw only. exceptions only.
Syntax The throw keyword is followed by an instance of The throws keyword is followed by class names of
Exception to be thrown. Exceptions to be thrown.
Declaration throw is used within the method. throws is used with the method signature.
Internal implementation We are allowed to throw only one exception at a We can declare multiple exceptions using throws
time i.e. we cannot throw multiple exceptions. keyword that can be thrown by the method. For
example, main() throws IOException,
SQLException.