Inheritance in Java: Subclasses & Superclasses
Inheritance in Java: Subclasses & Superclasses
Unit-3
Introduction to Inheritance
2. Inheritance Basics
2.1. Why use inheritance in java
2.2. Terms used in Inheritance
2.3. The syntax of Java Inheritance
3. Understanding the Types of Inheritance in java
3.1. Single Inheritance Example
3.2. Multilevel Inheritance Example
3.3. Hierarchical Inheritance Example
3.4. Why is multiple inheritance not supported in java?
4. Aggregation in Java
4.1. Why use Aggregation?
4.2. Simple Example of Aggregation
● A class that is derived from another class is called a subclass (also a derived class, extended
class, or child class).
● The class from which the subclass is derived is called a superclass (also a base class or a parent
class).
● Except for Object, which has no superclass, every class has one and only one direct superclass
(single inheritance).
● In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
● Classes can be derived from classes that are derived from classes that are derived from classes,
and so on, and ultimately derived from the topmost class, Object.
● The following program creates a superclass called A and a subclass called B. Notice how the
keyword extends is used to create a subclass of A.
Example:
[Link]();
[Link]();
//The subclass has access to all public members of its superclass.
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
[Link]("Contents of subOb: ");
[Link]();
[Link]();
[Link]();
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
Here, the subclass B includes all of the members of its superclass, A. This is why subOb can access i and
j and call showij( ). Also, inside sum( ), i and j can be referred to directly, as if they were part of B.
Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being a
superclass for a subclass does not mean that the superclass cannot be used by itself. Further, a subclass
can be a superclass for another subclass.
Syntax:
class subclass-name extends superclass-name {
// body of class
}
// Create a superclass.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
[Link](10, 12);
[Link]();
[Link]("Total is " + [Link]);
}
}
Output: This program will not compile because the reference to j inside the sum( ) method of B causes
an access violation. Since j is declared as private, it is only accessible by other members of its own class.
Subclasses have no access to it.
Example:
// This program uses inheritance to extend Box.
class Box {
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = [Link];
height = [Link];
depth = [Link];
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1;
height = -1;
depth = -1;
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// Here, Box is extended to include weight.
class BoxWeight extends Box {
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = [Link]();
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
[Link]("Weight of mybox2 is " + [Link]);
}
}
Output:
Note: A major advantage of inheritance is that once you have created a superclass that defines
the attributes common to a set of objects, it can be used to create any number of more specific
subclasses. Each subclass can precisely tailor its own classification.
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = [Link]();
[Link]("Volume of weightbox is " + vol);
[Link]("Weight of weightbox is " + [Link]);
[Link]();
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = [Link](); // OK, volume() defined in Box
[Link]("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox does not define a weight member. */
Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Box objects. Since
BoxWeight is a subclass of Box, it is permissible to assign plainbox a reference to the weightbox object.
It is important to understand that it is the type of the reference variable—not the type of the object that
it refers to—that determines what members can be accessed. That is, when a reference to a subclass
object is assigned to a superclass reference variable, you will have access only to those parts of the
object defined by the superclass. This is why plainbox can’t access weight even when it refers to a
BoxWeight object. If you think about it, this makes sense, because the superclass has no knowledge of
what a subclass adds to it. This is why the last
line of code in the preceding fragment is commented out. It is not possible for a Box reference to access
the weight field, because Box does not define one.
2. Inheritance Basics
● Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system).
● The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
● Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
● Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
● Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
● Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It
is also called a base class or a parent class.
● Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.
The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is
called child or subclass.
3. Understanding the Types of Inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In
java programming, multiple and hybrid inheritance is supported through interface only.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
3.1. Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog
class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){
[Link]("eating...");
}
}
class Dog extends Animal{
void bark(){
[Link]("barking...");
}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Output:
barking...
eating...
3.2. Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, the BabyDog class inherits the Dog class which again inherits the Animal class, so there is
a multilevel inheritance.
File: [Link]
class Animal{
void eat(){
[Link]("eating...");
}
}
class Dog extends Animal{
void bark(){
[Link]("barking...");
}
}
class BabyDog extends Dog{
void weep(){
[Link]("weeping...");
}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Output:
weeping...
barking...
eating...
When two or more classes inherit a single class, it is known as hierarchical inheritance. In the example
given below, Dog and Cat classes inherit the Animal class, so there is hierarchical inheritance.
File: [Link]
class Animal{
void eat(){
[Link]("eating...");
}
}
class Dog extends Animal{
void bark(){
[Link]("barking...");
}
}
class Cat extends Animal{
void meow(){
[Link]("meowing...");
}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link](); //[Link]
}}
Output:
meowing...
eating...
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B
classes have the same method and you call it from a child class object, there will be ambiguity when
calling the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time errors if you inherit 2
classes. So whether you have the same method or different, there will be a compile time error.
class A{
void msg(){
[Link]("Hello");
}
}
class B{
void msg(){
[Link]("Welcome");
}
}
class C extends A,B{ //suppose if it were
4. Aggregation in Java
If a class has an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship.
Consider a situation, an Employee object contains a lot of information such as id, name, email-Id etc. It
contains one more object named address, which contains its own information such as city, state, country,
zip code etc. as given below.
class Employee{
int id;
String name;
Address address; //Address is a class
...
}
In such a case, the Employee has an entity reference address, so the relationship is Employee HAS-A
address.
● Code reuse is also best achieved by aggregation when there is no is-a relationship.
● Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of
the objects involved; otherwise, aggregation is the best choice.
class Operation{
class Circle{
Operation op; //aggregation
double pi=3.14;
int rsquare=[Link](radius);
//code reusability (i.e. delegates the method call).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=[Link](5);
[Link](result);
}
}
Output:78.5
5. Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer to an immediate parent class
object.
Whenever you create the instance of a subclass, an instance of the parent class is created implicitly
which is referred to by a super reference variable.
In the above example, Animal and Dog both classes have a common property color. If
we print the color property, it will print the color of the current class by default. To
access the parent property, we need to use the super keyword.
In the above example Animal and Dog both classes have eat() method. If we call the eat()
method from Dog class, it will call the eat() method of Dog class by default because priority is given to
the local.
To call the parent class method, we need to use the super keyword.
animal is created
dog is created
Note: super() is added in each class constructor automatically by the compiler if there is no super() or
this().
● Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
● Method overriding is used for runtime polymorphism
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
class Bank{
int getRateOfInterest(){
return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){
return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){
return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){
return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
[Link]("SBI Rate of Interest: "+[Link]());
[Link]("ICICI Rate of Interest: "+[Link]());
[Link]("AXIS Rate of Interest: "+[Link]());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
1) Method overloading is used to increase the readability of Method overriding is used to provide the specific
the program. implementation of the method that is already provided by
its super class.
2) Method overloading is performed within class. Method overriding occurs in two classes that have an IS-A
(inheritance) relationship.
3) In case of method overloading, parameters must be In case of method overriding, parameters must be the
different. same.
4) Method overloading is the example of compile time Method overriding is the example of run time
polymorphism. polymorphism.
5) In java, method overloading can't be performed by Return type must be same in method overriding.
changing the return type of the method only. Return
type can be the same or different in method overloading.
But you must have to change the parameter.
● If a class has multiple methods having the same name but different in parameters, it is known as
Method Overloading. If we have to perform only one operation, having the same name of the
methods increases the readability of the program.
● Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.
class Adder{
static int add(int a,int b){
return a+b;}
static int add(int a,int b,int c){
return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}
Output:
22
33
class Adder{
static int add(int a, int b){
return a+b;}
static double add(double a, double b){
return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}}
Output:
22
24.9
Note: In Java, Method Overloading is not possible by changing the return type of the method only.
Ques: Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only because of
ambiguity.
class TestOverloading4{
public static void main(String[] args){
[Link]("main with String[]");}
public static void main(String args){
[Link]("main with String");}
public static void main(){
[Link]("main without args");}
}
Output:
class A {
void callme() {
[Link]("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
[Link]("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
[Link]("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
output:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
This program creates one superclass called A and two subclasses of it, called B and C. Subclasses B and
C override callme( ) declared in A. Inside the main( ) method, objects of type A, B, and C are declared.
Also, a reference of type A, called r, is declared. The program then in turn assigns a reference to each
type of object to r and uses that reference to invoke callme( ). As the output shows, the version of
callme( ) executed is determined by the type of object being referred to at the time of the call. Had it
been determined by the type of the reference variable, r, you would see three calls to A’s callme( )
method.
class Bike9{
class Bike{
final void run(){
[Link]("running");}
}
● The final keyword can be applied with the variables, a final variable that has no value is called
blank final variable or uninitialized final variable.
● It can be initialized in the constructor only. The blank final variable can be static also which will
be initialized in the static block only.
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
[Link]([Link]);
}
}
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal processing
about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A method which is declared as abstract and does not have implementation is known as an abstract
method.
11. Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
If you are not using any IDE, you need to follow the syntax given below:
The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package
within the same directory, you can use . (dot).
To Compile: javac -d . [Link] // The -d is a switch that tells the compiler where to put the class file
i.e. it represents destination. The . represents the current folder.
There are three ways to access the package from outside the package.
● import package.*; // all the classes and interfaces of this package will be accessible but not
subpackages.
Example:
package pack;
public class A{
//save by [Link]
package mypack;
import pack.*;
class B{
[Link]();
Output:Hello
Example:
package pack;
public class A{
//save by [Link]
package mypack;
import pack.A;
class B{
[Link]();
Output:Hello
● fully qualified name. // only declared class of this package will be accessible. Now there is no
need to import. But you need to use a fully qualified name every time when you are accessing
the class or interface.
Example:
package pack;
public class A{
//save by [Link]
package mypack;
class B{
[Link]();
}
}
Output:Hello
Note: If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Sequence:
Classes and packages are both means of encapsulating and containing the name space and scope of
variables and methods. Packages act as containers for classes and other subordinate packages.
Classes act as containers for data and code. The class is Java’s smallest unit of abstraction.
Because of the interplay between classes and packages, Java addresses four categories of visibility for
class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to produce the many
levels of access required by these categories.
Example:
13. Interfaces
● Interfaces are syntactically similar to classes, but they lack instance variables, and their methods
are declared without any body.
● Once it is defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces.
● To implement an interface, a class must create the complete set of methods defined by the
interface.
● By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.
● An interface in Java is a blueprint of a class. It has static constants and abstract methods.
● The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method bodies. It is used to achieve abstraction and multiple
inheritance in Java.
● In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
● Java Interface also represents the IS-A relationship.
● It cannot be instantiated just like the abstract class.
● Since Java 8, we can have default and static methods in an interface.
● Since Java 9, we can have private methods in an interface.
An interface is defined much like a class. This is the general form of an interface:
return-type method-name2(parameter-list);
// ...
return-type method-nameN(parameter-list);
● The Java compiler adds public and abstract keywords before the interface method. Moreover, it
adds public, static and final keywords before data members.
● In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.
Example:
interface printable{
void print();
[Link]("Hello");
[Link]();
Output: Hello
● Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create the
methods defined by the interface.
● The general form of a class that includes the implements clause looks like this:
// class-body
● If a class implements more than one interface, the interfaces are separated with a comma.
● If a class implements two interfaces that declare the same method, then the same method will
be used by clients of either interface.
● The methods that implement an interface must be declared public.
● Also, the type signature of the implementing method must match exactly the type signature
specified in the interface definition.
interface Callback {
}
class Client implements Callback {
● It is both permissible and common for classes that implement interfaces to define additional
members of their own. For example, the following version of Client implements callback( ) and
adds the method nonIfaceMeth( ):
void nonIfaceMeth() {
}
14. Exception Handling
Dictionary Meaning: 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.
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so that
the normal flow of the application can be maintained.
The core advantage of exception handling is to maintain the normal flow of the application. An exception
normally disrupts the normal flow of the application; that is why we need to handle exceptions.
The [Link] class is the root class of Java Exception hierarchy inherited by two subclasses:
Exception and Error.
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
● Checked Exception
● Unchecked Exception
● Error
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.
2) 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.
3) Error
“The Java programming language uses exceptions to handle errors and other exceptional events. “
Java provides five keywords that are used to handle the exception.
try The "try" keyword is used to specify a block where we should place an exception code. It means we
can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means we
can't use catch block alone. It can be followed by a finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in
the method. It doesn't throw an exception. It is always used with method signature.
The mechanism suggests incorporation of a separate error handling code that performs following tasks:
● Find the problem(hit the exception): select the part of code where run time error can occur.
● Inform that an error has occurred (throw the exception):When an error occurs within a method,
the method creates an object and hands it off to the runtime system. The object, called an
exception object, contains information about the error, including its type and the state of the
program when the error occurred. Creating an exception object and handing it to the runtime
system is called throwing an exception.
● Receive the error information (catch the exception): the runtime system attempts to find
something to handle it. When an appropriate handler is found, the runtime system passes the
exception to the handler. An exception handler is considered appropriate if the type of the
exception object thrown matches the type that can be handled by the handler. The exception
handler chosen is said to catch the exception.
● Take corrective action (handle the exception): after handling the exception in a related catch
block a proper code is required to take appropriate action for handling the exception and
resuming the code with any break..
Example:
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
Output:
There are given some scenarios where unchecked exceptions may occur. They are as follows:
int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
[Link]([Link]());//NullPointerException
If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string variable that has characters; converting this variable into digit will cause
NumberFormatException.
String s="abc";
int i=[Link](s);//NumberFormatException
a[10]=50; //ArrayIndexOutOfBoundsException
15. Java try block
● Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
● If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in a try block that will not throw an
exception.
● Java try block must be followed by either catch or finally block.
● The try block can have one or more statements that could generate an exception . If any one
statement generates an exception, the remaining statements in the block are skipped and
exception execution jumps to the catch block that is placed next to the try block.
● A try block must have at least one catch block that follows it immediately. It can have multiple
catch blocks. This is necessary when the try block has statements that may raise different types
of exceptions.
● Nested try catch block are similar to nested constructs. You can have one try catch block inside
another. Similarly, a catch block can contain try catch blocks . Is a lower level try catch block
does not have a matching catch handler, the outer try block is checked for it.
●
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
● Java catch block is used to handle the Exception by declaring the type of exception within the
parameter.
● The declared exception must be the parent class exception ( i.e., Exception) or the generated
exception type. However, the good approach is to declare the generated type of exception.
● The catch block must be used after the try block only. You can use multiple catch blocks with a
single try block.
● Each catch block is an exception handler and handles the type of exception indicated by its
argument.
● The argument type, ExceptionType, declares the type of exception that the handler can handle
and must be the name of a class that inherits from the Throwable class.
● The catch block contains code that is executed if and when the exception handler is invoked by
matching. The runtime system invokes the exception handler when the handler is the first one in
the call stack whose ExceptionType matches the type of the exception thrown. The system
considers it a match if the thrown object can legally be assigned to the exception handler's
argument.
● The catch statement takes the object of the exception class that refers to the exception caught,
as a parameter . Once the exception is caught, the statements with in the catch block are
executed.
● The scope of the catch block is restricted to the statements in the preceding try block only.
● Exception handlers can do more than just print error messages or halt the program. They can do
error recovery, prompt the user to make a decision, or propagate the error up to a higher-level
● In Java SE 7 and later, a single catch block can handle more than one type of exception. This
feature can reduce code duplication and lessen the temptation to catch an overly broad
exception. In the catch clause, specify the types of exceptions that block can handle, and
separate each exception type with a vertical bar (|):
●
●
● The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:
○ Prints out exception description.
○ Prints the stack trace (Hierarchy of methods where the exception occurred).
○ Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.
Example: without exception handling
Example:
public class TryCatchExample2 {
} Output:
[Link]: / by zero
rest of the code
Example: if an exception occurs in the try block, the rest of the block code will not execute.
public class TryCatchExample3 {
[Link]: / by zero
}
Example: to print a custom message on exception.
public class TryCatchExample5 {
}
Example to resolve the exception in a catch block.
public class TryCatchExample6 {
25
for example, along with try block, we also enclose exception code in a catch block.: the catch block
didn't contain the exception code. So, enclose exception code within a try block and use catch block
only to handle the exceptions.
public class TryCatchExample7 {
try
{
int data1=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception
}
[Link]("rest of the code");
}
}
A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler.
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException
must come before catch for Exception.
public class MultipleCatchBlock1 {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
} Output:
Arithmetic Exception occurs
rest of the code
try{
int a[]=new int[5];
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
In Java, using a try block inside another try block is permitted. It is called as nested try block. Every
statement that we enter a try block, context of that exception is pushed onto the stack.
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself
may cause another error. In such cases, exception handlers have to be nested.
17.2. Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
● Java finally block is a block used to execute important code such as closing the connection, etc.
● Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of whether the
exception occurs or not.
● The finally block follows the try-catch block.
● When exceptions are thrown, execution takes a rather abrupt, nonlinear path that alters the
normal flow through a method.
● It is quite possible that a method will return prematurely. This could be a problem.
● To avoid such problems finally keywords are designed to address such problems.
● Finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block.
● If an exception is thrown and no suitable match is found, the exception will go to the default
handler and the finally block will be executed.
● The finally block is a key tool for preventing resource leaks. When closing a file or otherwise
recovering resources, place the code in a finally block to ensure that resource is always
recovered.
● Finally clause is optional, however each try statement requires one catch or finally block.
● Finally block will not be executed only in one condition:
○ If the JVM exits while the try or catch code is being executed, then the finally block may
not execute. Likewise, if the thread executing the try or catch code is interrupted or
killed, the finally block may not execute even though the application as a whole
continues.
● finally block in Java can be used to put "cleanup" code such as closing a file, closing connection,
etc.
● The important statements to be printed can be placed in the finally block.
Let's see the below example where the Java program does not throw any exception, and the finally
block is executed after the try block.
Example:
class TestFinallyBlock {
try{
int data=25/5;
[Link](data);
catch(NullPointerException e){
[Link](e);
finally {
Case 2: When an exception occur but not handled by the catch block
Here, the code throws an exception however the catch block cannot handle it. Despite this, the finally
block is executed after the try block and then the program terminates abnormally.
Example:
try {
int data=25/0;
[Link](data);
catch(NullPointerException e){
[Link](e);
finally {
Example: Java code throws an exception and the catch block handles the exception. Later the finally
block is executed after the try-catch block. Further, the rest of the code is also executed normally.
try {
[Link]("Inside try block");
int data=25/0;
[Link](data);
catch(ArithmeticException e){
[Link]("Exception handled");
[Link](e);
finally {
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if the program exits (either by calling [Link]() or by
causing a fatal error that causes the process to abort).
19. Java throw Exception
In Java, exceptions allow us to write good quality code where the errors are checked at the compile time
instead of runtime and we can create custom exceptions making the code recovery and debugging
easier.
Where the Instance must be of type Throwable or subclass of Throwable. For example, Exception is the
subclass of Throwable and the user-defined exceptions usually extend the Exception class.
● The Java throws keyword is used to declare an exception. It gives information to the programmer
that there may occur an exception. So, it is better for the programmer to provide the exception
handling code so that the normal flow of the program can be maintained.
● Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is the programmers' fault that he is not
checking the code before it is being used.
● Sometimes, it's appropriate for code to catch exceptions that can occur within it. In other cases,
however, it's better to let a method further up the call stack handle the exception.
● if a method is capable of raising an exception that is does not handle or don’t want to handle, it
must specify that the exception has to be handled by the calling method.
● This is done using the throws statement. The throws statement is used to specify the list of
exceptions that are thrown by the method.
● The throws clause comprises the throws keyword followed by a comma-separated list of all the
exceptions thrown by that method. The clause goes after the method name and argument list
and before the brace that defines the scope of the method;
//method code
1. Definition Java throw keyword is used to Java throws keyword is used in the
the code, inside the function or the exception which might be thrown by
the code.
throw only.
thrown. thrown.
4. Declaration throw is used within the method. throws is used with the method
signature.
5. Internal We are allowed to throw only one We can declare multiple exceptions
implementation exception at a time i.e. we cannot using throws keyword that can be
SQLException.
1. Definition final is the keyword and finally is the block in Java finalize is the method in Java
used to apply restrictions execute the important code up processing just before
variable. or not.
2. Applicable Final keyword is used Finally block is always finalize() method is used with
to with the classes, methods related to the try and catch the objects.
3. Functionali (1) Once declared, final (1) finally block runs the finalize method performs the
constant and cannot be exception occurs or not. to the object before its
modified. destruction.
(2) finally block cleans up all
inherited.
4. Execution Final method is executed Finally block is executed as finalize method is executed
only when we call it. soon as the try-catch block is just before the object is
executed. destroyed.
Example: Final
void display() {
age = 55;
[Link]();
}
Example : finally
try {
int data=25/0;
[Link](data);
[Link]("Exception handled");
[Link](e);
finally {
Example: finalize
obj = null;
[Link]();
Consider the example 1 in which the InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have passed a
string to the constructor of superclass i.e. Exception class that can be obtained using getMessage()
method on the object we have created.
23.1. Why use custom exceptions?
Java exceptions cover almost all the general types of exceptions that may occur in the programming.
However, we sometimes need to create custom exceptions.
We need to write the constructor that takes the String as the error message and it is called parent class
constructor.