[Go to site: main page, start]

0% found this document useful (0 votes)
8 views63 pages

Inheritance in Java: Subclasses & Superclasses

Uploaded by

prbht0008
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)
8 views63 pages

Inheritance in Java: Subclasses & Superclasses

Uploaded by

prbht0008
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

SRM Institute of Science and Technology

NCR Campus, Modinagar

Department of Computer Applications

Program: [Link]. Computer Science


Course Name: Programming In Java
Course Code: USA20301J

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

5. Super Keyword in Java


[Link] of Java super Keyword

6. Method Overriding in Java


6.1. Usage of Java Method Overriding
6.2. Rules for Java Method Overriding
7. Method Overloading in Java
8. Dynamic Method Dispatch

9. Final Keyword In Java


11. Package
12. Access Protection
13. Interfaces
1. Introduction to Inheritance

● 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:

// A simple example of inheritance.


// Create a superclass.
class A {
int i, j;
void showij() {
[Link]("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
[Link]("k: " + k);
}
void sum() {
[Link]("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
[Link]("Contents of superOb: ");

[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]();

[Link]("Sum of i, j and k in subOb:");


[Link]();
}
}
OUTPUT:

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
}

1.1. Member Access and Inheritance


Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private

// 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]();

[Link]("Volume of mybox1 is " + vol);


[Link]("Weight of mybox1 is " + [Link]);
[Link]();

vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
[Link]("Weight of mybox2 is " + [Link]);
}
}

Output:

Volume of mybox1 is 3000.0


Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076

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.

1.2. A Superclass Variable Can Reference a Subclass Object


A reference variable of a superclass can be assigned a reference to any subclass derived from
that superclass.
Example:

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. */

// [Link]("Weight of plainbox is " + [Link]);


}
}

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.

2.1. Why use inheritance in java

● For Method Overriding (so runtime polymorphism can be achieved).


● For Code Reusability.

2.2. Terms used in Inheritance

● 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.

2.3. The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

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...

3.3. Hierarchical Inheritance Example

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...

3.4. Why is multiple inheritance not supported in java?

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

public static void main(String args[]){


C obj=new C();
[Link](); //Now which msg() method would be invoked?
}
}
Output: Compile Time Error

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.

4.1. Why use Aggregation?

● 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.

4.2. Simple Example of Aggregation


In this example, we have created the reference of Operation class in the Circle class.

class Operation{

int square(int n){


return n*n;
}
}

class Circle{
Operation op; //aggregation
double pi=3.14;

double area(int radius){


op=new Operation();

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.

[Link] of Java super Keyword


1. super can be used to refer to an immediate parent class instance variable:->
a. We can use super keywords to access the data member or field of the parent class. It is
used if parent class and child class have the same fields.
b. Example:
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
[Link](color); //prints color of Dog class
[Link]([Link]); //prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
Output:
black
white

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.

2. super can be used to invoke the immediate parent class method:->


a. The super keyword can also be used to invoke parent class methods.
b. It should be used if the subclass contains the same method as the parent class. In other
words, it is used if the method is overridden.
c. Example:
class Animal{
void eat(){
[Link]("eating...");
}
}
class Dog extends Animal{
void eat(){
[Link]("eating bread...");
}
void bark(){
[Link]("barking...");
}
void work(){
[Link]();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
Output :
eating...
Barking…

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.

3. super() can be used to invoke immediate parent class constructor:->


class Animal{
Animal(){
[Link]("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
[Link]("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:

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().

6. Method Overriding in Java


If a 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 classes, it is known as method overriding.

6.1. Usage of Java Method Overriding

● 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

6.2. Rules for Java Method Overriding

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).

6.3. A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However,
the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%,
7%, and 9% rate of interest.

Java method overriding example of bank

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

Ques: Can we override the static method?


Ans: No, a static method cannot be overridden. It can be proved by runtime polymorphism.
Ques: Why can we not override static methods?
Ans: It is because the static method is bound with class whereas the instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.
Ques: Can we override java main method?
Ans: No, because the main method is a static method.
6.4. Difference between method overloading and method overriding in java
[Link]. Method Overloading Method Overriding

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.

6) class OverloadingExample{ class Animal{


static int add(int a,int b){ void eat(){
return a+b;} [Link]("eating...");}
static int add(int a,int b,int c){ }
return a+b+c;} class Dog extends Animal{
} void eat(){
[Link]("eating bread...");}
}

7. Method Overloading in Java

● 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.

7.1. Advantage of method overloading


1. Method overloading increases the readability of the program.

7.2. Different ways to overload the method


There are two ways to overload the method in java:
● By changing number of arguments

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

● By changing the data type

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.

Ques: Can we overload java main() method?


Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls the main() method which receives string arrays as arguments only.

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:

main with String[]

7.3. Method Overloading and Type Promotion


One type is promoted to another implicitly if no matching data type is found.
Byte can be promoted to short, int, long, float or double. The short data type can be promoted to int,
long, float or double. The char data type can be promoted to int,long,float or double and so on.
8. Dynamic Method Dispatch
● Method overriding forms the basis for one of Java’s most powerful concepts: dynamic method
dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
● Dynamic method dispatch is important because this is how Java implements run-time
polymorphism.
● When an overridden method is called through a superclass reference, Java determines which
version of that method to execute based upon the type of the object being referred to at the time
the call occurs. Thus, this determination is made at run time.
● When different types of objects are referred to, different versions of an overridden method will
be called.
● In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed.
● Therefore, if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable, different
versions of the method are executed.

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

A r; // obtain a reference of type A


r = a; // r refers to an A object

[Link](); // calls A's version of callme


r = b; // r refers to a B object
[Link](); // calls B's version of callme
r = c; // r refers to a C object

[Link](); // calls C's version of callme


}
}

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.

9. Final Keyword In Java


● The final keyword in java is used to restrict the user. The java final keyword can be used in many
contexts.
● Final can be:
○ Variable

class Bike9{

final int speedlimit=90; //final variable


void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}
Output: Compile Time Error

○ Method:-> Cannot be overridden

class Bike{
final void run(){
[Link]("running");}
}

class Honda extends Bike{


void run(){
[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
[Link]();
}
} Output: Compile Time Error

○ Class :-> CANNOT BE EXTENDED

final class Bike{}

class Honda1 extends Bike{


void run(){
[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
[Link]();
}
} Output: Compile Time Error

● 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.

Ques: Is the final method inherited?


Ans) Yes, the final method is inherited but you cannot override it.

Ques: What is the blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating an object and once initialized may
not be changed, it is useful. For example, the PAN CARD number of an employee.
It can be initialized only in the constructor.

Ques: Can we declare a constructor final?


No, because the constructor is never inherited.

Ques: Can we initialize the blank final variable?


Yes, but only in constructor.

9.1. static blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static blocks.

class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
[Link]([Link]);
}
}

Ques: What is the final parameter?


If you declare any parameter as final, you cannot change the value of it.

10. Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).

10.1. Abstraction in Java

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.

10.2. Ways to achieve Abstraction

There are two ways to achieve abstraction in java

● Abstract class (0 to 100%)


● Interface (100%)

10.3. Points to Remember

● An abstract class must be declared with an abstract keyword.


● It can have abstract and non-abstract methods.
● It cannot be instantiated.
● It can have constructors and static methods also.
● It can have final methods which will force the subclass not to change the body of the method.

Syntax: abstract class A{}

10.4. Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract
method.

Syntax: abstract void printStatus();

11. Package

● A java package is a group of similar types of classes, interfaces and sub-packages.


● Packages in java can be categorized in two forms, built-in package and user-defined package.
● There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

11.1. Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collisions


11.2. How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example: javac -d . [Link]

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).

11.3. How to run java package program

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.

To Run: java [Link]

11.4. How to access a package from another package?

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{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

[Link]();

Output:Hello

● import [Link]; // only declared class of this package will be accessible

Example:

package pack;

public class A{

public void msg(){[Link]("Hello");}

//save by [Link]
package mypack;

import pack.A;

class B{

public static void main(String args[]){

A obj = new A();

[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{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();//using fully qualified name

[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:

12. Access Protection

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:

//This is file [Link]:


package p1;
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection() {
[Link]("base constructor");
[Link]("n = " + n);
[Link]("n_pri = " + n_pri);
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
}
}

//This is file [Link]:


package p1;
class Derived extends Protection {
Derived() {
[Link]("derived constructor");
[Link]("n = " + n);
// class only
// [Link]("n_pri = "4 + n_pri);
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
}
}
//This is file [Link]:
package p1;
class SamePackage {
SamePackage() {
Protection p = new Protection();
[Link]("same package constructor");
[Link]("n = " + p.n);
// class only
// [Link]("n_pri = " + p.n_pri);
[Link]("n_pro = " + p.n_pro);
[Link]("n_pub = " + p.n_pub);
}
}

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.

13.1. Why use the Java interface?

● It is used to achieve abstraction.


● By interface, we can support the functionality of multiple inheritance.
● It can be used to achieve loose coupling.

13.2. Defining an Interface

An interface is defined much like a class. This is the general form of an interface:

access interface name {


return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value;

// ...

return-type method-nameN(parameter-list);

type final-varnameN = value;

● 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.

13.3. The relationship between classes and interfaces

Example:

interface printable{

void print();

class A6 implements printable{


public void print(){

[Link]("Hello");

public static void main(String args[]){

A6 obj = new A6();

[Link]();

Output: Hello

13.4. Implementing Interfaces

● 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 classname [extends superclass] [implements interface [,interface...]] {

// 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.

Here is a small example class that implements the Callback interface:

//Declare Callback interface

interface Callback {

void callback(int param);

}
class Client implements Callback {

// Implement Callback's interface

public void callback(int p) {

// Notice that callback( ) is declared using the public access specifier.

[Link]("callback called with " + p);

● 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( ):

class Client implements Callback {

// Implement Callback's interface

public void callback(int p) {

[Link]("callback called with " + p);

void nonIfaceMeth() {

[Link]("Classes that implement interfaces " + "may also define other


members, too.");

}
14. Exception Handling

14.1. What is Exception in Java?

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.

14.2. Exception Handling

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.

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

14.3. Advantage of Exception Handling

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.

14.4. Hierarchy of Java Exception classes

The [Link] class is the root class of Java Exception hierarchy inherited by two subclasses:
Exception and Error.

14.5. Types of Java Exceptions

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

14.6. Difference between Checked and Unchecked Exceptions

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

● Error is irrecoverable. Some examples of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.
● Error handling becomes a necessity when you develop an application that needs to take care of
unexpected situations. The unexpected situations that may occur program execution are:
○ Running out of memory
○ Resources allocation errors.
○ Inability in network connectivity
○ Problems in network connectivity

“The Java programming language uses exceptions to handle errors and other exceptional events. “

● There are two types of error available in java:


○ Compile time exceptions: all syntax errors will be detected and displayed by java
compiler and therefore these errors are known as compile time errors. Whenever the
compiler displays an error , it will not create the .class file. It is therefore necessary that
we have to fix the errors before we can successfully compile and run the program.

○ Runtime exceptions: sometimes a program may compile successfully creating a .class
file but may not run properly. We call it an exception. an exception is a condition that is
caused by run time error in the program. When a java interpreter encounters an error
such as dividing by zero, it creates an exception object and throws it.

14.7. Java Exception Keywords

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.

throw The "throw" keyword is used to throw an exception.

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:

public class JavaExceptionExample{

public static void main(String args[]){

try{
//code that may raise exception

int data=100/0;

}catch(ArithmeticException e){[Link](e);}

//rest code of the program

[Link]("rest of the code...");

Output:

Exception in thread main [Link]:/ by zero

rest of the code…

14.8 Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

String s=null;

[Link]([Link]());//NullPointerException

3) A scenario where NumberFormatException occurs

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

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

int a[]=new int[5];

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.

Syntax of Java try-catch

try{
//code that may throw an exception

}catch(Exception_class_Name ref){}

15.1. Java catch block

● 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 (|):

15.2. Internal Working of Java try-catch block

● 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

public class TryCatchExample1 {

public static void main(String[] args) {


int data=50/0; //may throw exception

[Link]("rest of the code");

Example:
public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}

} 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 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
[Link]("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
Output:

[Link]: / by zero

Example: exception using the parent class exception.


public class TryCatchExample4 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
[Link](e);
}
[Link]("rest of the code");
}

}
Example: to print a custom message on exception.
public class TryCatchExample5 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
[Link]("Can't divided by zero");
}
}

}
Example to resolve the exception in a catch block.
public class TryCatchExample6 {

public static void main(String[] args) {


int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
[Link](i/(j+2));
}
}
}
Output:

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 {

public static void main(String[] args) {

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");
}
}

16. Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler.

16.1. Points to remember

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 {

public static void main(String[] args) {

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

public class MultipleCatchBlock2 {

public static void main(String[] args) {

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

17. Java Nested try block

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.

17.1. Why use nested try block

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
}
....

18. Java finally block

● 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.

18.1. Flowchart of finally block


Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if
any).

18.2. Why use Java finally?

● 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.

18.3. Usage of Java finally

Case 1: When an exception does not occur

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 {

public static void main(String args[]){

try{

//below code do not throw any exception

int data=25/5;
[Link](data);

//catch won't be executed

catch(NullPointerException e){

[Link](e);

//executed regardless of exception occurred or not

finally {

[Link]("finally block is always executed");

[Link]("rest of phe code...");

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:

public class TestFinallyBlock1{

public static void main(String args[]){

try {

[Link]("Inside the try block");


//below code throws divide by zero exception

int data=25/0;

[Link](data);

//cannot handle Arithmetic type exception

//can only accept Null Pointer type exception

catch(NullPointerException e){

[Link](e);

//executes regardless of exception occured or not

finally {

[Link]("finally block is always executed");

[Link]("rest of the code...");

Case 3: When an exception occurs and is handled by the catch block

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.

public class TestFinallyBlock2{

public static void main(String args[]){

try {
[Link]("Inside try block");

//below code throws divide by zero exception

int data=25/0;

[Link](data);

//handles the Arithmetic Exception / Divide by zero exception

catch(ArithmeticException e){

[Link]("Exception handled");

[Link](e);

//executes regardless of exception occured or not

finally {

[Link]("finally block is always executed");

[Link]("rest of the code...");

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.

19.1. Java throw keyword

● The Java throw keyword is used to throw an exception explicitly.


● We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.
● We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception. We will discuss custom exceptions later in this section.
● We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw an ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw an exception using throw keyword.
● The Java platform provides numerous exception classes. All the classes are descendants of the
Throwable class, and all allow programs to differentiate among the various types of exceptions
that can occur during the execution of a program.
● You can also create your own exception classes to represent problems that can occur within the
classes you write
● you may want to throw an exception explicitly when a user enters a wrong login ID or
password.
● All methods use the throw statement to throw an exception. The throw statement requires a
single argument: a throwable object. Throwable objects are instances of any subclass of
theThrowable class.
● The throw statement takes a single argument, which is an object of the exception.
● The throw statement is commonly used in programmer-defined exceptions.
● The flow of the program stops immediately after the throw statement, any subsequent
statements are not executed.
● Then look for catch statement that matches the type of exception, if a match is found then
control is transferred to that statement.
● If no suitable catch block is found then exception will be handled by default handler that halts
the program and print message and stack trace.
● all you need to remember is that you can throw only objects that inherit from the
[Link] class.

19.2. syntax of the Java throw keyword

throw Instance i.e.,

throw new exception_class("error message");


throw IOException.

throw new IOException("sorry device error");

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.

20. Java throws keyword

● 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;

20.1. Syntax of Java throws

return_type method_name() throws exception_class_name{

//method code

20.2. Which exception should be declared?

Ans: Checked exception only, because

● unchecked exception: under our control so we can correct our code.


● error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

20.3 Advantage of Java throws keyword

● Now Checked Exceptions can be propagated (forwarded in call stack).


● It provides information to the caller of the method about the exception.
● If we are calling a method that declares an exception, we must either caught or declare the
exception.
● There are two cases:
○ Case 1: We have caught the exception i.e. we have handled the exception using try/catch
block.
○ Case 2: We have declared the exception i.e. specified throws keyword with the method.
■ In case we declare the exception, if exception does not occur, the code will be
executed fine.
■ In case we declare the exception and the exception occurs, it will be thrown at
runtime because throws does not handle the exception.

21. Throw vs Throws

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is used to Java throws keyword is used in the

throw an exception explicitly in method signature to declare an

the code, inside the function or the exception which might be thrown by

block of code. the function while the execution of

the code.

2. Type of exception Using throws keyword, we can

Using throw keyword, declare both checked and

we can only propagate unchecked exceptions. However,

unchecked exception the throws keyword can be used

i.e., the checked to propagate checked exceptions

exception cannot be only.


propagated using

throw only.

3. Syntax The throw keyword is followed by The throws keyword is followed by

an instance of Exception to be class names of Exceptions to be

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

throw multiple exceptions. thrown by the method. For example,

main() throws IOException,

SQLException.

22. Final vs Finally vs Finalize

S Key final finally finalize


r.
n
o.

1. Definition final is the keyword and finally is the block in Java finalize is the method in Java

access modifier which is Exception Handling to which is used to perform clean

used to apply restrictions execute the important code up processing just before

on a class, method or whether the exception occurs object is garbage collected.

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.

and variables. block in exception handling.

3. Functionali (1) Once declared, final (1) finally block runs the finalize method performs the

ty variable becomes important code even if cleaning activities with respect

constant and cannot be exception occurs or not. to the object before its

modified. destruction.
(2) finally block cleans up all

(2) final method cannot be the resources used in try

overridden by sub class. block

(3) final class cannot be

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.

It's execution is not

dependant on the exception.

Example: Final

public class FinalExampleTest {

//declaring final variable

final int age = 18;

void display() {

// reassigning value to age variable

// gives compile time error

age = 55;

public static void main(String[] args) {

FinalExampleTest obj = new FinalExampleTest();

// gives compile time error

[Link]();
}

Example : finally

public class FinallyExample {

public static void main(String args[]){

try {

[Link]("Inside try block");

// below code throws divide by zero exception

int data=25/0;

[Link](data);

// handles the Arithmetic Exception / Divide by zero exception

catch (ArithmeticException e){

[Link]("Exception handled");

[Link](e);

// executes regardless of exception occurred or not

finally {

[Link]("finally block is always executed");

[Link]("rest of the code...");

Example: finalize

public class FinalizeExample {


public static void main(String[] args)

FinalizeExample obj = new FinalizeExample();

// printing the hashcode

[Link]("Hashcode is: " + [Link]());

obj = null;

// calling the garbage collector using gc()

[Link]();

[Link]("End of the garbage collection");

// defining the finalize method

protected void finalize()

[Link]("Called the finalize() method");

23. Java Custom Exception


In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our
own Exception is known as a custom exception or user-defined exception. Basically, Java custom
exceptions are used to customize the exception according to user need.

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.

Following are few of the reasons to use custom exceptions:

● To catch and provide specific treatment to a subset of existing Java exceptions.


● Business logic exceptions: These are the exceptions related to business logic and workflow. It is
useful for the application users or the developers to understand the exact problem.
● In order to create custom exceptions, we need to extend the Exception class that belongs to the
[Link] package.

You might also like