0% found this document useful (0 votes)
16 views40 pages

Inheritance

Inheritance basics, using super and final, method overriding, dynamic method dispatch, Abstract Class, Interface: variables and extending Interfaces, Package: Creating and importing packages, Package access protection, Exception Handling: Exception handling fundamentals, Exception types, Uncaught Exceptions Using try and catch, multiple catch clauses, nested try statements, throw, Java’s built-in exceptions.

Uploaded by

ankkumar835
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)
16 views40 pages

Inheritance

Inheritance basics, using super and final, method overriding, dynamic method dispatch, Abstract Class, Interface: variables and extending Interfaces, Package: Creating and importing packages, Package access protection, Exception Handling: Exception handling fundamentals, Exception types, Uncaught Exceptions Using try and catch, multiple catch clauses, nested try statements, throw, Java’s built-in exceptions.

Uploaded by

ankkumar835
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
You are on page 1/ 40

Introduction to Java Programming (4CS4-06)

Unit-3: Inheritance: Inheritance basics, using super and final, method overriding, dynamic method
dispatch, Abstract Class, Interface: variables and extending Interfaces, Package: Creating and
importing packages, Package access protection, Exception Handling: Exception handling
fundamentals, Exception types, Uncaught Exceptions Using try and catch, multiple catch clauses,
nested try statements, throw, Java’s built-in exceptions.

Inheritance: Inheritance is a mechanism in which one class can acquire the property of another
class. Inheritance is a mechanism in which one object acquires all the properties and behaviors of
a parent object. The idea behind inheritance is to create new classes that are built upon existing
classes.
The new class that is created is known as subclass (child or derived class) and the existing class
from where the child class is derived is known as superclass (parent or base class).
Through inheritance, a subclass can access members of its superclass.

Why inheritance?
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

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.

Single Inheritance: In this a sub-class is derived from only one super class or when a class inherits
another class, it is known as a single inheritance. . It is also known as simple inheritance.

Class Abc Super class (Parent)

inherits

Class Abc1 Sub Class (Child)


Multilevel Inheritance: In this a class is derived from a class which is also derived from another
class is called multilevel inheritance. In this type of inheritance, each class in the hierarchy inherits
properties and behavior from its immediate superclass.
Class Abc Super class (Parent)

inherits

Class Abc1 Sub Class/intermediate base class

inherits

Class Abc2
Derived Class

Hierarchical inheritance: If a number of classes are derived from a single base class is called
hierarchical inheritance. It allows multiple classes to share common properties and behavior
defined in the superclass.

Class Abc Super class (Parent)

Class Abc1 Class Abc2 Class Abc3 Derived


Classes

Java doesn't support multiple inheritance to avoid the 'diamond problem', where ambiguity
arises when a class inherits from two classes with the same method names. Instead, Java uses
interfaces to achieve similar functionality while maintaining clarity and simplicity.

Hybrid Inheritance: It is a combination of two or more types of inheritance. In hybrid


inheritance, a class is derived from two or more classes, and these derived classes can further have
their own subclasses. Java doesn’t support multiple inheritance directly due to the diamond
problem, but hybrid inheritance can be achieved by combining hierarchical inheritance and
interface implementation.
Class Abc
Single inheritance

Class Abc1
Single inheritance Heirarchical

Inheritace
Class Abc2 Class Abc3 Class Abc4

Syntax of inheritance in Java is as follows:


class BaseClass
{
// properties and methods of the base class
}
class SubClass extends BaseClass
{
// properties and methods of the derived class
}

The extends keyword indicates that we are making a new class that derives from an existing
class. The meaning of “extends” is to increase the functionality.

e.g.
class Abc
{
//Data members
//member function
}
class Sub extends Abc
{
//Data members
//member function
}

//1. Program for the implementation of single inheritance in Java


Class Exam
{
int a,b;
void disp()
{
System.out.println(“Base class”+”\na=”+a+”\nb=”+b);
}
}
class Exam1 extends Exam
{
int c;
Exam1()
{
a=10;
b=20;
c=30;
}
void disp1()
{
System.out.println(“From derived class”+”\na=”+a+”\nb=”+b+”\nc=”+c);
}
}
class Test
{
public static void main(String r[])
{
Exam1 ob=new Exam1();
ob.disp();
ob.disp1();
}
}

//2.Program for the implementation of single inheritance in Java


class Calc
{
int s;
void add(int a,int b)
{
s=a+b;
System.out.println(“\nSum=”+s);
}
void sub(int a,int b)
{
s=a-b;
System.out.println(“\nDifference=”+s);
}
}
class Calc1 extends Calc
{
void multiply(int a,int b)
{
s=a*b;
System.out.println(“\nProduct=”+s);
}
}

class Exam
{
public static void main(String r[])
{
Calc1ob=new Calc1();
ob.add(10,30);
ob.sub(34,9);
ob.multiply(9,7);
}
}

//3.Program for the implementation of multilevel inheritance in Java


class Abc //Base class
{
void disp()
{
System.out.println(“class Abc method”);
}
}

class Abc1 extends Abc //intermediate base class and derived class
{
void disp1()
{
System.out.println(“class Abc1 method”);
}
}

class Abc2 extends Abc1 //derived class


{
void disp2()
{
System.out.println(“class Abc2 method”);
}
}
class Test
{
public static void main(String r[])
{
Abc2 ob=new Abc2();
ob.disp();
ob.disp1();
ob.disp2();
}
}

//4.Program for the implementation of hierarchical inheritance in Java


We are writing the program where class B, C and D extends class A.
class A
{
public void dispA()
{
System.out.println("Method of Class A");
}
}
class B extends A
{
public void dispB()
{
System.out.println("Method of Class B");
}
}
class C extends A
{
public void dispC()
{
System.out.println("Method of Class C");
}
}
class D extends A
{
public void dispD()
{
System.out.println("Method of Class D");
}
}
class Exam
{
public static void main(String r[])
{
B ob1 = new B();
C ob2 = new C();
D ob3 = new D();
//All classes can access the method of class A
ob1.dispA();
ob1.dispB();
ob2.dispA();
ob2.dispB();
ob3.dispA();
}

Output:
Method of Class A
Method of Class B
Method of Class A
Method of Class C
Method of Class A

//5.Program in Java that shows repetition of code


class Abc
{
int a,b;
Abc() //parameterless constructor
{
a=b=0;
}
Abc(int i) //parameterized constructor
{
a=b=i;
}
Abc(int i,int j) //parameterized constructor
{
a=i;
b=j;
}
void disp()
{
System.out.println("\na="+a+”\nb=”+b);
}
}
class Abc1 extends Abc
{
int c;
Abc1() //parameterless constructor
{
a=b=c=0;
}
Abc1(int i) //parameterized constructor
{
a=b=c=i;
}
Abc1(int i,int j,int k) //parameterized constructor
{
a=i;
b=j;
c=k;
}
void disp1()
{
System.out.println("\na="+a+”\nb=”+b+”\nc=”+c);
}
}

class Test
{
public static void main(String r[])
{
Abc1 ob1=new Abc1();
Abc1 ob2=new Abc1(10);
Abc1 ob3=new Abc1(10,20,30);
ob1.disp1();
ob1.disp();
ob2.disp1();
ob3.disp1();
}
}

*In the above program class derived from Abc is not implemented as efficiently or robustly as
they could have been. The constructor Abc(), Abc(int i) explicitly initializes a,b. Not only this
duplicate code found in superclass, which is inefficient but subclass must be granted access to
these members.

Super keyword in Java:


We want create a superclass that keeps the details of its implementation to itself (i.e. keep its data
members private). In this case, there would be no way for a subclass to directly access or initialize
these variables on its own.
But Java provides a solution to the problem. Whenever a subclass needs to refer to its immediate
superclass, it can do by use of super keyword.
The super keyword in Java is used to refer to the immediate super class object. It is commonly
used to access parent class methods and constructors, enabling a subclass to inherit and reuse the
functionality of its superclass.

Usage of super keyword:


 Call the superclass constructor
 To access a member (data member or member function) of superclass that has been
hidden by a member of subclass.

Syntax
super(); // call the superclass constructor
super.methodName(); //call superclass method
super.datamember; //superclass data member

1.To call superclass constructor:


Syntax: super(arg-list);
super() must be the first statement executed inside a subclass constructur.
class Abc
{
int a,b;
Abc() //parameterless constructor
{
a=b=0;
}
Abc(int i) //parameterized constructor
{
a=b=i;
}
Abc(int i,int j) //parameterized constructor
{
a=i;
b=j;
}
void disp()
{
System.out.println("\na="+a+”\nb=”+b);
}
}
class Abc1 extends Abc
{
int c;
Abc1() //parameterless constructor
{
super(); //call superclass constructor
c=0;
}
Abc1(int i) //parameterized constructor
{
super(i); //call superclass constructor
c=i;
}
Abc1(int i,int j,int k) //parameterized constructor
{
super(i,j); //call superclass constructor

c=k;
}
void disp1()
{
System.out.println("\na="+a+”\nb=”+b+”\nc=”+c);
}
}

class Test
{
public static void main(String r[])
{
Abc1 ob1=new Abc1();
Abc1 ob2=new Abc1(10);
Abc1 ob3=new Abc1(10,20,30);
ob1.disp1();
ob1.disp();
ob2.disp1();
ob3.disp1();
}
}

2.To access the member of superclass that has been hidden by the member of
subclass:
The super keyword can also be used to invoke parent class data member/method. It should be
used if subclass contains the same data member/method as parent class.

Syntax: super.member // member is either instance variable or method


class Abc
{
int a,b;
Abc() //parameterless constructor
{
a=b=0;
}
Abc(int i) //parameterized constructor
{
a=b=i;
}
Abc(int i,int j) //parameterized constructor
{
a=i;
b=j;
}
void disp()
{
System.out.println("\na="+a+”\nb=”+b);
}
}

class Abc1 extends Abc


{
int c;
Abc1() //parameterless constructor
{
super(); //call superclass constructor
c=0;
}
Abc1(int i) //parameterized constructor
{
super(i); //call superclass constructor
c=i;
}
Abc1(int i,int j,int k) //parameterized constructor
{
super(i,j); //call superclass constructor

c=k;
}
void disp()
{
super.disp(); //call superclass method
System.out.println("\nc=”+c);
}
}

class Test
{
public static void main(String r[])
{
Abc1 ob1=new Abc1();
Abc1 ob2=new Abc1(10);
Abc1 ob3=new Abc1(10,20,30);
ob1.disp();
ob2.disp();
ob3.disp();
}
}

When Constructor are called:


In a class hierarchy, constructor are called in the order of derivation, i.e. from superclass to
subclass. Since super() must be the first statement executed in a subclass constructor, this order is
the same whether or not super() is used. If super() in not used, then the default(parameterless)
constructor of each superclass will be executed.

e.g.
class A
{
A()
{
System.out.println("Class A constructor:”);
}
}
class B extends A
{
B()
{
System.out.println("Class B constructor:”);
}
}
class C extends B
{
C()
{
System.out.println("Class C constructor:”);
}
}

class Test
{
public static void main(String r[])
{
C ob = new C();
}
}

Output:
Class A constructor
Class B constructor
Class C constructor

Method Overriding:
When a method in a subclass has the same name, parameters or signature and return type as a
method in its superclass, then the method in the subclass override the method in the super class.
When a overridden method is called from within a subclass, it will always refer to the version of
the method defined by the subclass. The version of the method defined by the superclass will be
hidden.
Method overriding is used to create a specific implementation of a method that is already present
in the parent class. It also provides multiple implementation of the same method.

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java or If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding:


 Method overriding is used to provide the specific implementation of a method that is
already provided by its superclass.
 Method overriding is used for runtime polymorphism.
 Method overriding allows subclasses to reuse and build upon the functionality provided
by their superclass, reducing redundancy and promoting modular code design.
Method Overloading Method Overriding
Compile time polymorphism Run polymorphism
Occurs within the class Occurs between two classes using
inheritance
Method must have same name but Method must have same name and
different signature signature
It is used to increase the readability of the It is used to provide the specific
program implementation of the method that is
already provided by the superclass

// Program in Java for the implementation of Method overriding


class Abc
{
int a,b;
Abc(int i,int j)
{
a=i;
b=j;
}
void calc()
{
int s;
s=a+b;
System.out.println("Sum:”+s);
}
}

class Abc1 extends Abc


{
Abc1(int i,int j)
{
super(i,j);
}
void calc()
{
int s;
super.calc(); //The overridden method is called from a subclass using the super keyword
s=a*b;
System.out.println("Product:”+s);
}
}
class Test
{
public static void main(String r[])
{
Abc1 ob = new Abc1(10,20);
ob.calc();
}
}

Why overridden methods?


Method overriding in Java support run-time polymorphism. Polymorphism allows a general class
to specify methods that will be common to all its derivatives, while allowing subclasses to define
the specific implementation of some or all of those methods. So method overriding is a way that
Java implements “one interface multiple methods” aspect of polymorphism.

Dynamic method dispatch:


Method overriding is one of the ways in which Java supports run-time polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved
at run-time, rather at compile time.
Java uses the principle of “A superclass reference variable can refer to a subclass object” to resolve
calls to overridden methods at run time. When a superclass reference is used to call an overridden
method, Java determines which version of the method to execute based on the type of object being
referenced to at the time of call.
Dynamic method dispatch or run-time polymorphism is the mechanism through which the correct
version of an overridden method is called at runtime. When a subclass overrides a method from its
superclass, the overridden method in the subclass is executed when called on an instance of the
subclass, even if the reference to the object is of the superclass type.

Upcasting :
It is a technique in which a superclass reference variable refers to the object of the subclass.
e.g.
class A
{
void disp()
{
System.out.println("class A method”);
}
}

class B extends A
{
void disp() //override disp()
{
System.out.println("class B method”);
}
}

class C extends A
{
void disp() //override disp()
{
System.out.println("class C method”);
}
}

class Test
{
public static void main(String r[])
{
A oa=new A(); //object of class A
B ob=new B(); //object of class B
C oc=new C(); //object of class C
A ref; //reference of A, initially it will point to null
ref=oa; //refer to class A object
ref.disp(); //calling A version
ref=ob; //refer to class B object
ref.disp(); //calling B version
ref=oc; //refer to class C object
ref.disp(); //calling C version
}
}

Abstract class in Java:


Data abstraction is the process of hiding certain details and showing only essential information to the
user.
There are two ways to achieve abstraction in Java:
 Using Abstract Class
 Using Interface
Sometimes we want to create a superclass that only defines a generalized form that will be
shared by of its subclasses, leaving it to each subclass to fill in the details. Such a class
determines the nature of the methods that the subclasses must implement.
An abstract class acts as a partially implemented class that itself cannot be instantiated. It exists
only for subclassing purposes, and provides a template for its subclasses to follow. Abstract classes
can have implementations with abstract methods. Abstract methods are declared to have no body,
leaving their implementation to subclasses.
A class which is declared with the abstract keyword is known as an abstract class. It can have
abstract and non-abstract methods. An abstract method is a method which is declared without any
implementation. The abstract class hide the internal details of method, showing only essential
information to the user- the method name.

Any subclass of an abstract class must either implement all of the abstract methods in the
superclass or be itself declared abstract.
Java abstract class is used to provide common method implementation to all the subclasses.

 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:
public abstract class Shape
{
public abstract double area(); // Abstract method

public void display() // Concrete method


{
System.out.println("This is a shape.");
}
}
*Subclasses of Shape class must implement the area() method, but they can inherit the display()
method.

//Program in Java for the implementation of abstract class


abstract class Shape
{
float a,b;
Shape(float i, float j)
{
a=i;
b=j;
}
abstract void area(); //abstract method
}

class Rectangle extends Shape


{
Rectangle(float i, float j)
{
Super(i,j);
}
void area() //override area
{
float s;
s=a*b;
System.out.println("Area of rectangle:"+s);
}
}

class Triangle extends Shape


{
Triangle(float i, float j)
{
Super(i,j);
}
void area() //override area
{
float s;
s=(a*b)/2;
System.out.println("Area of tritangle:"+s);
}
}

class Test
{
public static void main(String r[])
{
float a=3.4, b=2.6;
Rectangle or=new Rectangle(a,b);
Tritangle ot=new Triangle(a,b);
or.area();
ot.area();
}
}

Interfaces:
Interfaces are similar to classes but they lack instance variables and their methods are declared
without body.
It is a blueprint of a class and contains set of abstract and public methods we want our classes to
implement.
Interfaces are used to achieve abstraction and implement multiple inheritance.
All the methods in interfaces are public and abstract by default (no need to use explicitly abstract
keyword).
Using interface we can specify what a class must do but not how it does it. Once defined any
number of classes can implement an interface. One class can implement any number of
interfaces(multiple inheritance).
Any class implementing an interface will need to provide implementation of methods defined by
interface. Each class is free to determine the details of its own implementation.
Interfaces are designed to support dynamic method resolution at run time. If a method is calles
from one class to another, both classes need to be present at compile time so compiler can check
to ensure that the method signatures are compatible. Interfaces are designed to avoid this problem.
They disconnect the definition of a method from the inheritance hierarchy. Classes are unrelated
in terms of class hierarchy to implement the same interface.

Syntax:
access interface <interface-name>
{
type final-var1=value;
type final-var2=value;
return-type method1(parameter-list);
return-type method2(parameter-list);
}
Where:
access – It is default of public
final-var1, final-var-2 – these are the variables they are implicitly final (cannot be changed).
They must be initialized.
*All methods and variables are implicitly public.

e.g.
interface Shape
{
double PI=3.14;
void area();
}

Implementing interfaces:
To implement an interface, include implements clause in a class definition and then create
methods defined by the interface.

Syntax:
class <class-name> [extends superclass] [implements interface1, interface………]
{
-
-
}

e.g.
interface Shape
{
void area();
}

class Rectangle implements Shape


{
int l,b;
Rectangle(int i, int j)
{
l=i;
b=j;
}
public void area() //override area
{
int s;
s=l*b;
System.out.println("Area of rectangle:"+s);
}
}

class Triangle implements Shape


{
int a,b;
Triangle(float i, float j)
{
a=i;
b=j;
}
public void area() //override area
{
float s;
s=(a*b)/2;
System.out.println("Area of tritangle:"+s);
}
}

class Test
{
public static void main(String r[])
{
float a=3.4, b=2.6;
Rectangle or=new Rectangle(4,5);
Triangle ot=new Triangle(a,b);
or.area();
ot.area();
}
}

Multiple inheritance in Java:


In Java one class can implements any number of interfaces or an interface extends multiple
interfaces, it is known as multiple inheritance.

Interface 1 Interface 2

implements
class

Interface 1 Interface 2

extends
Interface 3

An interface can extend other interface, just a class extend another class. However a class can
extend only one superclass, but an interface can extend any number of interfaces in Java.

Syntax:
interface Abc
{
-
-
}
interface Abc1
{
-
-
}
interface Abc2 extends Abc1,Abc2
{
-
-
}

e.g.
interface Test
{
void disp();
}

interface Test1
{
void disp1();
}
interface Test2 extends Test, Test1
{
void disp2();
}
//class Exam implements methods from interfaces Test, Test1 & Test2
class Exam implements Test2
{
void disp()
{
System.out.println("Method of Test”);
}
void disp1()
{
System.out.println("Method of Test1”);
}
void disp2()
{
System.out.println("Method of Test2”);
}
}

class Main
{
public static void main(String r[])
{
Exam ob=new Exam();
ob.disp();
ob.disp1();
ob.disp2();
}
}

Packages in Java:
A package is a group of similar types of classes, interfaces and sub-packages.
It helps to organize classes into a folder structure and make it easy to locate and use them.
It helps to improve code reusability.
The package is both a naming and a visibility control mechanism. We can define classes inside a
package that are not accessible by code outside that package.
We can also define class members that are only exposed to other members of the same package.
This allows classes to have intimate knowledge to each other, but not expose that knowledge to
the rest of the world.
Advantages of Java Packages:
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 collision.

Types of Packages:
1. Built-in Packages
2. User defined Packages

Built-in Packages:
The built-in packages are the packages from Java API. The Java API is a library of pre-defined
classes, interfaces and sub-packages. The built-in packages were included in JDK. These packages
contains a large number of classes and interfaces useful for different requirements. We can import
these packages in any Java program and can use the classes and interfaces of these packages in
that program.
There are many built-in packages in Java- java, util, io, lang, awt, swing etc.

java.awt : Contains classes for creating user interfaces and for painting graphics and images.
Classes like Button, Color, Event, Font, Graphics, Image etc are part of this package.

java.io : Provides classes for system input/output operations. Classes like BufferedReader,
BufferedWriter, File, InputStream, OutputStream, PrintStream, Serializable etc are part of this
package.

java.lang : Contains classes and interfaces that are fundamental to the design of Java
programming language. Classes like String, StringBuffer, System, Math, Integer etc are part of
this package.

java.net : Provides classes for implementing networking applications. Classes


like Authenticator, HttpCookie, Socket, URL, URLConnection, URLEncoder, URLDecoder etc
are part of this package.

java.sql : Provides the classes for accessing and processing data stored in a database. Classes
like Connection, DriverManager, PreparedStatement, ResultSet, Statement etc are part of this
package.

java.util : Contains the collections framework, some internationalization support classes,


properties, random number generation classes. Classes like ArrayList, LinkedList, HashMap,
Calendar, Date, TimeZone etc are part of this package.
Importing packages:
To import the Java package into a class, we need to use the import statement which is used to
access the package and its classes into the Java program. The import statement is used to import
built-in and user-defined packages.
The import statement must be after the package statement and before any other statement.
Using an import statement we may import a specific class or all the classes from a package.

There is a need to import the built-in packages to use them in a program. To import a package we
use import statement.
The import keyword is used to make the classes and interface of another package accessible to
the current package.

Syntax:
import packagename.classname; //import single class
import packagename.*; //import whole package

If you use packagename.* then all the classes and interfaces of this package will be accessible
but not sub-packages.

If you import package.classname then only declared class of this package will be accessible.

User-defined Package:
The user-defined packages are the packages created by the user. User is free to create their own
packages.
To create a package – include a package command as the first statement in any Java source file.
Any class declared within that file will belong to the specified package. There can be only one
package statement in each source file.
If a package statement is not used then the classes, interfaces will be placed in the current default
package.

Syntax:
package pkgname;
pkgname – name of package

e.g.
package cs; //create a package cs

We can also create a hierarchy of packages.


General form:
package pkg1[.pkg2][.pkg3];
e.g.
package cs.cs1; //create a sub-package cs1 within package cs

1. //create user defined package


package cs;
public class Test //class is stored in package cs
{
//class body
}

2.//create user defined sub-package


package cs.cs1;
public class Test //class is stored in sub-package cs1
{
//class body
}

Access protection Java:


In Java access modifiers define the accessibility of the class and its members. The class act as
a container of data and methods. So the access modifier decides the accessibility of class
members across the different packages.
There are four types of access modifiers in Java:
1. private: The access level of private modifier is only within the class. It cannot be accessed
from outside the class.
2. default: The access level is only within the package. It cannot be accessed from outside
the package. If we do not specify any access level, it will be the default.
3. protected: The access level is within the package and outside the package through
subclass. If we do not make subclass it cannot be accessed from outside the package.
4. public: It can be accessed from within the class, outside the class, within the package and
outside the package.

Access Modifier Within class Within package Outside package Outside package
subclass non-subclass
private Y N N N
default Y Y N N
protected Y Y Y N
public Y Y Y Y
//Program in Java for the implementation of package
package cs;
public class Test
{
private int a=10;
int b=20;
protected int c=30;
public int d=40;

void disp()
{
System.out.println(“Inside main parent class:”);
System.out.println(“\na=”+a+”\nb=”+b+”\nc=”+c+”\nd=”+d);
}
}

//Same package subclass


package cs;
public class Test1 extends Test
{
void disp1()
{
System.out.println(“Same package Sub class:”);
System.out.println(”\nb=”+b+”\nc=”+c+”\nd=”+d);
}
}

//Same package non-subclass


package cs;
public class Test2
{
void disp2()
{
Test ob=new Test();
System.out.println(“Same package non-subclass:”);
System.out.println(”\nb=”+ob.b+”\nc=”+ob.c+”\nd=”+ob.d);
}
}

//Different package subclass


package cs1;
import cs.Test; //import Test class of cs package
public class Test3 extends Test
{
void disp3()
{
System.out.println(“Different package Sub class:”);
System.out.println(”\nc=”+c+”\nd=”+d);
}
}

//Different package non-subclass


package cs1;
import cs.Test; //import Test class of cs package
public class Test4
{
void disp4()
{
Test ob=new Test();
System.out.println(“Different package non-subclass:”);
System.out.println(”\nd=”+ob.d);
}
}

//Main class
import cs.*;
import cs1.*;
class Exam
{
public static void main(String r[])
{
Test ob1=new Test();
Test1 ob2=new Test1();
Test2 ob3=new Test2();
Test3 ob4=new Test3();
Test4 ob5=new Test4();
ob1.disp();
ob2.disp1();
ob3.disp2();
ob4.disp3();
ob5.disp4();
}
}

Exception Handling:
An Exception is an unwanted or unexpected event that occurs during the execution of a program
(i.e., at runtime) and disrupts the normal flow of the program. It occurs when something
unexpected things happen, like accessing an invalid array index, dividing by zero, or trying to
open a file that does not exist. When an exception occurs, it is represented by an object of a subclass
of the java.lang.Exception class.

Exception handling is a mechanism to handle run-time errors so that normal flow program can be
maintained.

Exceptions can be caught and handled by the program. When an exception arises, an object
representing that exception is created and thrown in the method that caused the error. The object
is called exception object. It contains information about the exception such as name and description
of the exception.

Advantages of exception handling:


The advantage of exception handling is to maintain the normal flow of program i.e. prevent
program from abnormal termination. (An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions.)

Exception hierarchy:
All exceptions are subclasses of class Throwable, which is the base class of hierarchy.
One branch is headed by Exception- This class is used for exceptional conditions that the program
should catch. e.g. ArithmeticException

Another is headed by Error to indicate errors having that are not expected to be caught.
e.g. StackOverflow
Throwable

Exception Error

IOException StackOverflowError

SQLException
OutOfMemoryError
ClassNotFoundException

RuntimeException

ArithmeticException

NullPointerException

NumberFormatException

ArrayIndexOutOfBoundsEx
ception

Types of Exceptions in Java:


In Java, exceptions are categorized into two main types: checked exceptions and unchecked
exceptions. Additionally, there is a third category known as errors.
1. Checked Exception
2. Unchecked Exception
3. Error

1. Checked Exceptions
Checked exceptions are the exceptions that are checked at compile-time. This means that the
compiler verifies that the code handles these exceptions either by catching them or declaring them
in the method signature using the throws keyword.
IOException: An exception is thrown when an input/output operation fails, such as when reading
from or writing to a file.

SQLException: It is thrown when an error occurs while accessing a database.

ParseException: Indicates a problem while parsing a string into another data type, such as parsing
a date.

ClassNotFoundException: It is thrown when an application tries to load a class but the class
with the specified name cannot be found.

2. Unchecked Exceptions (Runtime Exceptions)


Unchecked exceptions, also known as runtime exceptions, are not checked at compile-time. These
exceptions usually occur due to programming errors, such as logic errors or incorrect assumptions
in the code. They do not need to be declared in the method signature using the throws keyword,
making it optional to handle them.

NullPointerException: It is thrown when trying to access or call a method on an object reference


that is null.
String s=null;
System.out.println(s.length());//NullPointerException

ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an


invalid index.
int a[]=new int[6];
a[10]=80; //ArrayIndexOutOfBoundsException

ArithmeticException: It is thrown when an arithmetic operation fails, such as division by zero.


int a=30/0; //ArithmeticException
3. Errors
Errors represent exceptional conditions that are not expected to be caught under normal
circumstances. They are typically caused by issues outside the control of the application, such as
system failures or resource exhaustion. Errors are not meant to be caught or handled by application
code.
OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot allocate enough
memory for the application.

StackOverflowError: It is thrown when the stack memory is exhausted due to excessive


recursion.
NoClassDefFoundError: It indicates that the JVM cannot find the definition of a class that was
available at compile-time.
Java exception handling is managed via five keywords – try, catch, throw, throws and finally.

1. try block:
 Program statements to monitor for exceptions are contained within a try block.
 A try block cannot be executed on itself; it requires at least one catch block or finally
block.
 If an exception occurs, the control flows from the try-to-catch block.
 When an exception occurs in a try block, the appropriate exception object is redirected to
the catch block. This catch block handles the exception according to its statements and
continues the execution.

Syntax
try
{
// block of code monitor for exception.
}

2. catch block:
 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.
 The catch block handles the exception raised in the try block.
 The catch block or blocks follow every try block.
 The catch block catches the thrown exception and executes the statements inside it.

Syntax
try
{
// block of code monitor for exception.
}
catch(Exception e)
{
// code to handle exceptions
}

//Java exception example without try/catch(uncaught exception)


class Test
{
public static void main(String r[])
{
int a,b=0;
a=5/b;
System.out.println(“a=’+a);
}
}
Java run-time system detect attempt to divide by zero. It construct a new exception object and
then throw the exception. This causes execution of Test class to stop, because when an exception
is thrown, it must be caught by an exception handler. Any exception that is not caught by our
program ill be processed by the default exception handler. The default handler displays a string
describing the exception:
java.lang.ArithmeticException:/ be zero at Test.main(Test.java:6)

Suppose we want to handle exception ourself. It provides two benefits:


 It allows to fix the error
 It prevent program from abnormal termination.
To handle exception enclose the code that we want to monitor inside a try block and following try,
include a catch clause that specifies the exception type that we want to catch.

//Java exception handling example using try/catch


class Test
{
public static void main(String r[])
{
int a,b=0;
try
{
a=5/b;
System.out.println(“a=”+a);
}
catch(ArithemeticException e)
{
System.out.println(“Divide by zero”);
}
System.out.println(“After try/catch”);
}

Output:
Divide by zero
After try/catch
//Another program for Java exception handling using try/catch
import java.util.*
class Test
{
public static void main(String r[])
{
int a,b,s;
Scanner ob=new Scanner(System.in);
try
{
System.out.println(“Enter value for a and b”);
a=ob.nextInt();
b=ob.nextInt();
s=a/b;
System.out.println(“s=”+s);
}
catch(ArithemeticException e)
{
System.out.println(“Divide by zero”);
}
System.out.println(“After try/catch”);
}
Displaying description of exception:
catch(ArithemeticException e)
{
System.out.println(“Exception:”+e);
}
Output:
Exception: java.lang.ArithmeticException:/ be zero

//Another program for Java exception handling using try/catch


class Test
{
public static void main(String r[])
{
try
{
int a[]={2,4,6};
System.out.println(“value:”+a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Exception :”+e);
}
}

Output:
Exception:ArrayIndexOutOfBounsException

Multiple Catch blocks:


In Java more than one exception can be raised by a single piece of code. To handle such situation,
we can specify two or more catch blocks each catching a different type of exception.
At a time only one exception occurs and only catch block is executed, the others are bypassed.
All catch blocks must be ordered from most specific to most general i.e. ArithmeticException
must come before catch for Exception.

//Java program using multiple catch blocks


import java.util.*
class Test
{
public static void main(String r[])
{
int a,b,s;
int c[]=[2,3,4};
Scanner ob=new Scanner(System.in);

try
{
System.out.println(“Enter value for a and b”);
a=ob.nextInt();
b=ob.nextInt();
s=a/b;
System.out.println(“s=”+s);
System.out.println(“Value:”+c[3]);
}
catch(ArithemeticException e)
{
System.out.println(“Divide by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Exception :”+e);
}
catch(Exception e)
{
System.out.println(“Exception :”+e);
}
System.out.println(“After try/catch”);
}

*When we use multiple catch blocks, exception subclasses must come before any of their
superclass. This is because a catch statement that uses a superclass will catch exception of that
type plus any of its subclasses. Thus a subclass would never be reached if it come after its
superclass. In Java unreachable code is an error.

3. throw clause:
In Java it is possible to throw an exception explicitly, using throw statement. The throw keyword
is used to throw an exception explicitly. The flow of execution stops immediately after the throw
statement, any subsequent statements are not executed.
Syntax:
throw throwableinstance; //throwableinstance is an object of type Throwable or subclass
of Throwable
There are two ways to obtain a Throwable object: using a parameter in a catch block or creating
one with new operator.
e.g.
throw new ArithmeticException("/ by zero");
Instance must be of type Throwable or a subclass of Throwable.

//Java program for the implementation of throw statement


import java.util.*;
class Test
{
public static void main(String r[])
{
int a,b,s;
Scanner ob=new Scanner(System.in);
System.out.println(“Enter value for a and b”);
a=ob.nextInt();
b=ob.nextInt();
try
{
if(b==0)
throw new ArithmenticException(“Divide by zero”);
else
{
s=a/b;
System.out.println(“s=”+s);
}
}
catch(ArithemeticException e)
{
System.out.println(“Divide by zero”);
}
}
}

4. throws clause:
It is used in the method signature to indicate that the method may throw mentioned exceptions. A
throws clause lists the types of exceptions that a method might throw. It is used only with checked
exceptions.
*If a method causing an exception but does handle that exception, then the method must specify
the behavior so that the caller of the method can guard themselves against that exception.

Syntax:
return-type method() throws eception1, exception2,---
{
//body of the method
}

//program for the implementation of throws clause


import java.util.*;
class Test
{
int a,b;
Test(int i,int j)
{
a=i; b=j;
}
void calc() throws ArithmeticException
{
int s;
s=(a+5)/b;
System.out.println(“s=”+s);
}
}

class Exam
{
public static void main(String r[])
{
int a,b;
Scanner ob=new Scanner(System.in);
System.out.println(“Enter value for a and b”);
a=ob.nextInt();
b=ob.nextInt();
Test ob=new Test(a,b);
try
{
ob.calc();
}
catch(ArithemeticException e)
{
System.out.println(“Exception:”+e);
}
System.out.println(“After try/catch:”);
}
}

Difference between throw and throws clause:


throw throws
It is used to explicitly throw an It is used in method signature to declare an exception
exception that the method may throw
It is used within the method It is used within the method signature
Can throw only a single exception Can declare multiple exceptions
Can be used to throw both checked and Can be used only with checked exceptions.
unchecked exceptions
Syntax: Syntax:
throw throwableinstance; return-type method() throws exception1,
exception2,---
{
//body of the method
}

5. finally:
The finally block contains block of code that will execute regardless of whether the exception has
occurred or not. Java finally block is always executed even if there are no exceptions. It is an
optional block. The finally block executes after try..catch block. It is used to execute important
statements such as releasing resources, and releasing memory.
Syntax:
try {
// Code that may throw an exception
}
catch (ExceptionType e)
{
// Code to handle the exception
}
finally
{
// Code that will always execute
}

//Java program for the implementation of finally block


public class Test
{
public static void main(String[] args)
{
try
{
int d = 50 / 0; // This will throw an ArithmeticException
}
catch (ArithmeticException e)
{
System.out.println("Exception caught: " + e);
}
finally
{
System.out.println("Finally block is always executed");
}
System.out.println(“After try/catch:”);

}
}
//Java program for the implementation of finally block
public class Test
{
public static void main(String[] args)
{
int a=5,b;
try
{
int b = 50 / a;
System.out.println("b=”+b);
}
catch (ArithmeticException e)
{
System.out.println("Exception caught: " + e);
}
finally
{
System.out.println("Finally block is always executed");
}
System.out.println(“After try/catch:”);
}
}

Java’s built-in exceptions:


Built-in exceptions are the exceptions that are available in Java libraries.
1. ArithmeticException : It is thrown when an exceptional condition has occurred in an
arithmetic operation.
2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed
with an illegal index. The index is either negative or greater than or equal to the size of the
array.
3. ClassNotFoundException : This Exception is raised when we try to access a class whose
definition is not found.
4. FileNotFoundException : This Exception is raised when a file is not accessible or does not
open.
5. IOException : It is thrown when an input-output operation failed or interrupted
6. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
7. NoSuchMethodException : It is thrown when accessing a method which is not found.
8. NullPointerException : This exception is raised when referring to the members of a null
object. Null represents nothing
9. NumberFormatException : This exception is raised when a method could not convert a string
into a numeric format.

You might also like