0% found this document useful (0 votes)
11 views45 pages

22CS202-Unit 2 Notes

Uploaded by

SHREE LEKHA
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)
11 views45 pages

22CS202-Unit 2 Notes

Uploaded by

SHREE LEKHA
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/ 45

22CS202 – Java Programming (Theory Course with Lab Component)

UNIT – II

INHERITANCE, INTERFACES AND EXCEPTION HANDLING


Inheritance: Inheritance basics, Using super, Method Overriding, Using Abstract Classes,
Using final with Inheritance - Package and Interfaces: Packages, Packages and member access,
Importing Packages, Interfaces, Static Methods in an Interface – Exception Handling:
Exception-Handling Fundamentals, Exception Types, Uncaught Exceptions, Using try and
catch, Multiple catch Clauses, Nested try Statements, throw, throws, finally, Java’s Built-in
Exceptions.

2.1 Inheritance in Java

Inheritance can be defined as the process of acquiring all the properties and behaviors of one
class to another. Acquiring the properties and behavior of child class from the parent class.
Inheritance represents the IS-A relationship, also known as parent-child relationship. 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.

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.

Example
• As displayed in the figure, Programmer is the subclass and
Employee is the superclass.
• The relationship between the two classes is Programmer IS-A
Employee.
• It means that Programmer is a type of Employee.

Syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

1
22CS202 – Java Programming (Theory Course with Lab Component)

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.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;

public static void main(String args[]){


Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Types of inheritance in java

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

2
22CS202 – Java Programming (Theory Course with Lab Component)

Single Inheritance

Single inheritance enables a derived class to inherit properties and behaviour from a single
parent class. It allows a derived class to inherit the properties and behaviour of a base class,
thus enabling code reusability as well as adding new features to the existing code.

Example: /* Java program to print student details using "single inheritance"*/


import java.util.Scanner;
class StudentDetails
{
introll_no;
Stringname, cl;
void input() //creating a method to take student details
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Roll Number: ");
roll_no = sc.nextInt();
System.out.print("Enter Name: ");
name = sc.nextLine();
System.out.print("Enter class: ");
cl = sc.nextLine();
}
}
class Student extends StudentDetails
{
void display() //method to display student details
{
System.out.println("/******* Student details printed ********/");
System.out.println("Roll Number is: "+roll_no);
System.out.println("Your name is: "+name);
System.out.println("Your class is: "+cl);
}
public static void main(String args[])

3
22CS202 – Java Programming (Theory Course with Lab Component)

{
Studentobj = newStudent();
obj.input();
obj.display();
}
}

Output
Enter Roll Number: 22
Enter Name: Coder Website
Enter class: 12th
/******* Student details printed ********/
Roll Number is: 22
Your name is: Coder Website
Your class is: 12th

Multi-level Inheritance

The multi-level inheritance includes the involvement of at least two or more than two
classes. One class inherits the features from a parent class and the newly created sub-class
becomes the base class for another new class.

Example

class students
{
private int sno;
private String sname;
public void setstud(int no,String name)
{
sno = no;
sname = name;
}
public void putstud()
{
System.out.println("Student No : " + sno);
System.out.println("Student Name : " + sname);
}
}
class marks extends students
{
protected int mark1,mark2;

4
22CS202 – Java Programming (Theory Course with Lab Component)

public void setmarks(int m1,int m2)


{
mark1 = m1;
mark2 = m2;
}
public void putmarks()
{
System.out.println("Mark1 : " + mark1);
System.out.println("Mark2 : " + mark2);
}
}
class finaltot extends marks
{
private int total;
public void calc()
{
total = mark1 + mark2;
}
public void puttotal()
{
System.out.println("Total : " + total);
}
public static void main(String args[])
{
finaltot f = new finaltot();
f.setstud(100,"Elon");
f.setmarks(78,89);
f.calc();
f.putstud();
f.putmarks();
f.puttotal();
}
}

Output
Student No : 100
Student Name : Elon
Mark1 : 78
Mark2 : 89
Total : 167

Hierarchical inheritance

When two or more derived class inherits the properties and behavior from same parent class.
It is known as hierarchical inheritance.

In other words, when several classes inherit their features from the same class, the type of
inheritance is said to be hierarchical.

When two or more classes inherits a single class, it is known as hierarchical inheritance.

5
22CS202 – Java Programming (Theory Course with Lab Component)

Example:
/ * This program is used for Hierarchical inheritance example. */
class Numbers
{
int a = 10;
int b = 20;
}
class AddNumbers extends Numbers
{
/* This method is used to add */
public void showAdd()
{
System.out.println(a + b);
}
}
class MultiplyNumbers extends Numbers
{
/* This method is used to multiply. */
public void showMultiplication()
{
System.out.println(a * b);
}
}
class Test
{
public static void main(String args[])
{
//creating base classes objects
AddNumbers obj1 = new AddNumbers();
MultiplyNumbers obj2 = new MultiplyNumbers();
//method calls
obj1.showAdd();
obj2.showMultiplication();
}
}

Output
30
200

6
22CS202 – Java Programming (Theory Course with Lab Component)

2.2 Super keyword in java

The super keyword refers to the objects of immediate parent class.

Characteristics of Super Keyword


• In Java, the term super keyword refers to the parent class of a subclass.
• It can be used to access or invoke parent-class objects from within the subclass.
• This contains constructors, methods, and variables from the parent class.
• If the subclass does not specify its own constructor, the parent class function will be
called automatically using super().
• Super can also be used to reach parent class instance variables or methods that the
subclass has hidden.
• When used with methods, super is used to invoke the parent class method rather than
the subclass's overridden method.

The super keyword in Java is used in the following scenarios


1. super can be used to refer to a variable of the immediate parent class
2. super can be used to invoke the immediate parent class method.
3. super can be used to access the immediate parent class constructor.

1. Use of super keyword with variable


• The super keyword in Java can be used to access the parent class instance variable.
• The Super keyword is very useful when both child and parent classes have the same
data members.
• If both child and parent classes have the same data member, then there is a possibility
of ambiguity for Java Virtual Machine (JVM) which can be avoided using super
keyword.

Accessing the num variable of parent class:


By calling a variable like this, we can access the variable of parent class if both the classes
(parent and child) have same variable.
super.variable_name;

Example
/* Parent class */
class ParentClass
{
int num = 120;
}
/* sub class childClass extending parentClass */
class ChildClass extends ParentClass
{
int num = 100;
void display()
{
//printing the num without use of super keyword
System.out.println("Value of Num in child class: " + num);
// printing the num with use of super keyword
System.out.println("Value of Num in parent class: " + super.num);
}

7
22CS202 – Java Programming (Theory Course with Lab Component)

}
class Main{
public static void main(String[] args)
{
ChildClass a = new ChildClass();
a.display();

}
}

Output:
Value of Num in child class: 100
Value of Num in parent class: 120

2. Use of super keyword with methods


• Super keyword in Java can also be used to invoke the parent class method.
• The super keyword is used when both child and parent classes have the same method,
and we want to call the parent class method.
• When a parent class and child class have the same method, the parent class method is
overridden by the child class method called as method overriding in Java.
• If we want to call the parent class method in a child class, we should use super keywords
to achieve this.

When we create the object of sub class, the new keyword invokes the constructor of
child class, which implicitly invokes the constructor of parent class. So, the order to execution
when we create the object of child class is: parent class constructor is executed first and then
the child class constructor is executed.
It happens because compiler itself adds super()(this invokes the no-arg constructor of
parent class) as the first statement in the constructor of child class.

Example
/* Parent class */
class ParentClass
{
void function()
{
System.out.println("This is method of parent class");
}
}

/* sub class childClass extending parentClass */


class ChildClass extends ParentClass
{
void function()
{
System.out.println("This is method of child class");
}
void display()
{ //will inwoke parent class function()
super.function();

8
22CS202 – Java Programming (Theory Course with Lab Component)

//will invoke current(child class) function()


function();
}
}
class Main{
public static void main(String[] args)
{
ChildClass a=new ChildClass();
a.display();
}
}

Output:
This is method of parent class
This is method of child class

3. Use of super with constructors


• The super keyword in Java can also be used to call or invoke the parent class
constructor.
• Super can be used to call both parametrized as well as non-parameterized constructors.

Example

/* Parent class */
class ParentClass
{
//parent class constructor
ParentClass()
{
System.out.println("This is constructor parent class");
}
}
/* sub class childClass extending parentClass */
class ChildClass extends ParentClass
{
//child class constructor
ChildClass()
{
//call parent constructor
super();
System.out.println("This is constructor of child class");
}
}

Output:
This is constructor parent class
This is constructor of child class

2.3 Method Overriding

9
22CS202 – Java Programming (Theory Course with Lab Component)

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

Usage of Java Method Overriding


1. Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
2. Method overriding is used for runtime polymorphism.

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)

Example

class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
@Override
public void displayInfo() {
System.out.println("I am a dog.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}

Simple Calculator using method overriding

import java.util.Scanner;
interface maths
{
public void add();
public void sub();
public void mul();
public void div();
}
class Arithmetic implements maths
{
@Override
public void add()
{

10
22CS202 – Java Programming (Theory Course with Lab Component)

Scanner kb = new Scanner(System.in);


System.out.println("Enter any two integer values to perform addition");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a + b;
System.out.println("Sum of "+a+" and "+b+" is "+s);
}
@Override
public void sub()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values to perform subtraction");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a - b;
System.out.println("Difference of "+a+" and "+b+" is "+s);
}
@Override
public void mul()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values multiplication");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a * b;
System.out.println("Product of "+a+" and "+b+" is "+s);
}
@Override
public void div()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values division");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a / b;
System.out.println("Quotient of "+a+" and "+b+" is "+s);
}
} // Arithmetic
public class Main
{

public static void main(String[] args)


{
Arithmetic obj = new Arithmetic();
obj.add();
obj.sub();
obj.mul();
obj.div();
} // main()
} // Main

11
22CS202 – Java Programming (Theory Course with Lab Component)

Output:

Enter any two integer values to perform addition


10
10
Sum of 10 and 10 is 20
Enter any two integer values to perform subtraction
20
10
Difference of 20 and 10 is 10
Enter any two integer values multiplication
10
10
Product of 10 and 10 is 100
Enter any two integer values division
1000
10
Quotient of 100 and 10 is 10

super keyword in case of method overriding

When a child class declares a same method which is already present in the parent class then
this is called method overriding.

Example
class Parentclass
{
//Overridden method
void display()
{
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
//Overriding method
void display()
{
System.out.println("Child class method");
}
void printMsg(){
//This would call Overriding method
display();
//This would call Overridden method
super.display();
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printMsg();

12
22CS202 – Java Programming (Theory Course with Lab Component)

}
}

Output:
Child class method
Parent class method

Advantages of Super Keyword in Java


• Allows access to parent class members such as instance variables, instance methods,
and constructors.
• Enables reuse of code that already exists in the parent class.
• Facilitates method overriding by allowing a subclass to call the parent class's version
of an overridden method using super.
• Provides a way to explicitly call a specific constructor of a superclass when creating
an instance of the subclass.
• Can be used to resolve name conflicts between subclass members and parent classes.
• Maintains inheritance relationships between classes, making your code cleaner and
easier to understand.
• It makes your code more flexible and extensible, making future changes and
extensions easier.

2.4 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). In Java, a separate
keyword abstract is used to make a class abstract. An abstract class cannot be instantiated. To
access the members of an abstract class, we must inherit it.

Example of abstract class


abstract class A
{
}

abstract class Shape


{
int a=3,b=4;
abstract void Area();
}
class Rectangle extends shape

13
22CS202 – Java Programming (Theory Course with Lab Component)

{
int rectarea;
void Area()
{
rectarea=a*b;
System.out.println(“Area of rectangle is:“ +rectarea);
}
}
class Triangle extends Shape
{
int triarea;
void Area()
{
triarea=(int) (0.5*a*b);
System.out.println(“Area of triangle is:“ +triarea);
}
}
class Circle extends Shape
{
int circlearea;
void Area()
{
circlearea=(int) (3.14*a*a);
System.out.println(“Area of circle is:“+circlearea);
}
}
public class Demo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Area();
Triangle t=new Triangle();
t.Area();
Circle c=new Circle();
c.Area();
}
}

Abstract class – features

➢ In Java, an instance of an abstract class cannot be created.


➢ An abstract class can contain constructors in Java. It is called when an instance of a
inherited class is created.
➢ In Java, we can have an abstract class without any abstract method. This allows us to
create classes that cannot be instantiated, but can only be inherited.
➢ But, if a class has at least one abstract method, then the class must be declared abstract.
➢ Abstract classes can also have final methods (methods that cannot be overridden).

Abstract Method in Java

14
22CS202 – Java Programming (Theory Course with Lab Component)

A method which is declared as abstract and does not have implementation is known as an
abstract method. They are declared with the purpose of having the sub class provide
implementation. They must be declared within an abstract class.
abstract void Methodname(); //no body of method hence

syntax

modifier abstract class SuperClassName


{
//declare fields
//declare methods
abstract returnType methodName();
}

modifier class ChildClassName extends SuperClassName


{
returnType methodName()
{
}
}

Example

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Example of abstract method


abstract void printStatus(); //no method body and abstract

Example 1

abstract class Multiply


{
// abstract methods
// sub class must implement these methods
public abstract intMultiplyTwo (int n1, int n2);
public abstract intMultiplyThree (int n1, int n2, int n3);
// regular method with body
public void show()

15
22CS202 – Java Programming (Theory Course with Lab Component)

{
System.out.println ("Method of abstract class Multiply");
}
}
// Regular class extends abstract class
class AbstractMethodEx1 extends Multiply
{
// if the abstract methods are not implemented, compiler will give an error
public intMultiplyTwo (int num1, int num2)
{
return num1 * num2;
}
public intMultiplyThree (int num1, int num2, int num3)
{
return num1 * num2 * num3;
}
// main method
public static void main (String args[])
{
Multiply obj = new AbstractMethodEx1();
System.out.println ("Multiplication of 2 numbers: " + obj.MultiplyTwo (10, 50));
System.out.println ("Multiplication of 3 numbers: " + obj.MultiplyThree (5, 8, 10));
obj.show();
}
}

Output
Multiplication of 2 numbers: 500
Multiplication of 3 numbers: 400
Method of abstract class Multiply

2.5 Using final keyword with inheritance in Java

➢ The final keyword is final that is we cannot change.


➢ We can use final keywords for variables, methods, and class.
➢ If we use the final keyword for the inheritance that is if we declare any method with the
final keyword in the base class so the implementation of the final method will be the
same as in derived class.
➢ We can declare the final method in any subclass for which we want that if any other
class extends this subclass.

Declare final variable with inheritance

// Declaring Parent class


class Parent {
/* Creation of final variable pa of string type i.e
the value of this variable is fixed throughout all
the derived classes or not overidden*/
final String pa = "Hello , We are in parent class variable";
}

16
22CS202 – Java Programming (Theory Course with Lab Component)

// Declaring Child class by extending Parent class


class Child extends Parent {
/* Creation of variable ch of string type i.e
the value of this variable is not fixed throughout all
the derived classes or overidden*/
String ch = "Hello , We are in child class variable";
}
class Test {
public static void main(String[] args) {
// Creation of Parent class object
Parent p = new Parent();
// Calling a variable pa by parent object
System.out.println(p.pa);
// Creation of Child class object
Child c = new Child();
// Calling a variable ch by Child object
System.out.println(c.ch);
// Calling a variable pa by Child object
System.out.println(c.pa);
}
}
Output
Hello , We are in parent class variable
Hello , We are in child class variable
Hello , We are in parent class variable

Declare final methods with inheritance

// Declaring Parent class


class Parent {
/* Creation of final method parent of void type i.e
the implementation of this method is fixed throughout
all the derived classes or not overidden*/
final void parent() {
System.out.println("Hello , we are in parent method");
}
}
// Declaring Child class by extending Parent class
class Child extends Parent {
/* Creation of final method child of void type i.e
the implementation of this method is not fixed throughout
all the derived classes or not overidden*/
void child() {
System.out.println("Hello , we are in child method");
}
}
class Test {
public static void main(String[] args) {
// Creation of Parent class object
Parent p = new Parent();

17
22CS202 – Java Programming (Theory Course with Lab Component)

// Calling a method parent() by parent object


p.parent();
// Creation of Child class object
Child c = new Child();
// Calling a method child() by Child class object
c.child();
// Calling a method parent() by child object
c.parent();
}
}

Output
Hello , we are in parent method
Hello , we are in child method
Hello , we are in parent method

2.6 Interface in Java

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

Declare an interface

An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static, and final by default. A class that implements an interface must implement all the methods
declared in the interface.

Syntax

interface <interface_name>
{
// declare constant fields
// declare methods that abstract by default.
}

The relationship between classes and interfaces

18
22CS202 – Java Programming (Theory Course with Lab Component)

As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Implementing an Interface in Java

Once the interface is declared, we can use it in a class using the “implements” keyword in
the class declaration. This ‘implements’ keyword appears after the class name as shown
below:

class <class_name> implements <interface_name>


{
//class body
}

Interface Implementation Example


//interface declaration
interface Polygon_Shape
{
void calculateArea(int length, int breadth);
}
//implement the interface
class Rectangle implements Polygon_Shape
{
//implement the interface method
public void calculateArea(int length, int breadth)
{
System.out.println("The area of the rectangle is " + (length * breadth));
}
}
public class Main
{
public static void main(String[] args)
{
Rectangle rect = new Rectangle(); //declare a class object
rect.calculateArea(10, 20); //call the method
}
}

Output
The area of rectangle is 200

Multiple Inheritance

19
22CS202 – Java Programming (Theory Course with Lab Component)

Multiple inheritance in java is the capability of creating a single class with multiple super
classes. Unlike some other popular object-oriented programming languages like C++, java
does not provide support for multiple inheritance in classes.

/* Program to implement the Multiple Inheritance */


class student
{
int regno;
String name,address;
void get(int rno,String n,String add)
{
regno=rno;
name=n;
address=add;
}
void display()
{
System.out.println(“Register number = “+regno);
System.out.println(“Name = “+name);
System.out.println(“Address = “+address);
}
}
Interface marks
{
void getmarks();
void displaymarks();
}
class result extends student implements marks
{
int m1,m2,m3,tot,avg;
void getmarks(int mk1,int mk2,int mk3)
{
m1=mk1;
m2=mk2;
m3=mk3;
}
void displaymarks()
{
tot=m1+m2+m3;
avg=tot/3;
System.outprintln(“Total = “+tot);
System.outprintln(“Average = “+avg);
}

20
22CS202 – Java Programming (Theory Course with Lab Component)

}
class multipledemo
{
public static void main(String args[])
{
result r=new result();
r.get(10,”kumar”,”Chennai”);
r.getmarks(60,70,80);
r.display();
r.displaymarks();
}
}

Output

Register number = 10
Name = kumar
Address = Chennai
Total = 210
Average = 70

Hybrid Inheritance

• In Java, the hybrid inheritance is the composition of two or more types of inheritance.
• The main purpose of using hybrid inheritance is to modularize the code into well-
defined classes. It also provides the code reusability.
• The hybrid inheritance can be achieved by using the following combinations:
• Single and Multiple Inheritance (not supported but can be achieved through
interface)
• Multilevel and Hierarchical Inheritance
• Hierarchical and Single Inheritance
• Multiple and Multilevel Inheritance

Single and Multiple Inheritance

class HumanBody {
public void displayHuman() {
System.out.println("Method defined inside HumanBody class"); }
}
interface Male {
public void show();

21
22CS202 – Java Programming (Theory Course with Lab Component)

}
interface Female {
public void show();
}
public class Child extends HumanBody implements Male, Female {
public void show() {
System.out.println("Implementation of show() method defined in interfaces
Male and Female");
}
public void displayChild() {
System.out.println("Method defined inside Child class");
}
public static void main(String args[])
{
Child obj = new Child();
System.out.println("Implementation of Hybrid Inheritance in Java");
obj.show();
obj.displayChild();
}
}

Using Multilevel and Hierarchical Inheritance

//parent class
class GrandFather {
public void showG() {
System.out.println("He is grandfather.");
} }
//inherits GrandFather properties
class Father extends GrandFather {
public void showF() {
System.out.println("He is father.");
} }
//inherits Father properties
class Son extends Father {
public void showS() {
System.out.println("He is son.");

22
22CS202 – Java Programming (Theory Course with Lab Component)

} }
//inherits Father properties
public class Daughter extends Father {
public void showD() {
System.out.println("She is daughter.");
}
public static void main(String args[]) {
Son obj = new Son();
obj.showS(); // Accessing Son class method
obj.showF(); // Accessing Father class method
obj.showG(); // Accessing GrandFather class method
Daughter obj2 = new Daughter();
obj2.showD(); // Accessing Daughter class method
obj2.showF(); // Accessing Father class method
obj2.showG(); // Accessing GrandFather class method
} }
Hierarchical and Single Inheritance

class C {
public void disp() {
System.out.println("C"); }
}
class A extends C {
public void disp()
{
System.out.println("A");}
}
class B extends C {
public void disp() {
System.out.println("B"); }
}
public class D extends A {
public void disp() {
System.out.println("D"); }
public static void main(String args[]) {
D obj = new D();
obj.disp(); }
}

Multiple and Multilevel Inheritance

23
22CS202 – Java Programming (Theory Course with Lab Component)

Static methods in an interface

•Static Methods in Interface are those methods, which are defined in the interface with
the keyword static.
• Unlike other methods in Interface, these static methods contain the complete definition
of the function and since the definition is complete and the method is static, therefore
these methods cannot be overridden or changed in the implementation class.
• Like Default Method in Interface, the static method in an interface can be defined in
the interface, but cannot be overridden in Implementation Classes.
• To use a static method, Interface name should be instantiated with it, as it is a part of
the Interface only.
When to use Interface?

Consider using an interface in the following cases:


• When you want to achieve 100% abstraction.
• If you want to achieve multiple inheritance, that is, implementing more than one
interface.
• When you want to specify the behavior of a particular data type irrespective of who
implements its behavior.

When an Abstract Class Implements an Interface?

• In the section on Interface, it was noted that a class that implements an interface must
implement all the interface's methods.
• It is possible, however, to define a class that does not implement all the interface's
methods, provided that the class is declared to be abstract. For example,
abstract class X implements Y {
// implements all but one method of Y
}
class XX extends X {
// implements the remaining method in Y
}
• In this case, class X must be abstract because it does not fully implement Y, but class
XX does, in fact, implement Y.

Example

24
22CS202 – Java Programming (Theory Course with Lab Component)

interface my_interface
{
static void static_fun()
{
System.out.println("In the newly created static method");
}
void method_override(String str);
}
public class Demo_interface implements my_interface
{
public static void main(String[] args)
{
Demo_interfacedemo_inter = new Demo_interface();
my_interface.static_fun();
demo_inter.method_override("In the override method");
}
@Override
public void method_override(String str)
{
System.out.println(str);
}
}

Output
In the newly created static method
In the override method

Java program to demonstrate static method in Interface.

• A simple static method is defined and declared in an interface which is being called in
the main() method of the Implementation Class InterfaceDemo.
• Unlike the default method, the static method defines in Interface hello(), cannot be
overridden in implementing the class.

interface NewInterface {
// static method
static void hello()
{
System.out.println("Hello, New Static Method Here");
}
// Public and abstract method of Interface
void overrideMethod(String str);
}

// Implementation Class
public class InterfaceDemo implements NewInterface {
public static void main(String[] args)
{
InterfaceDemo interfaceDemo = new InterfaceDemo();
// Calling the static method of interface

25
22CS202 – Java Programming (Theory Course with Lab Component)

NewInterface.hello();

// Calling the abstract method of interface


interfaceDemo.overrideMethod("Hello, Override Method here");
}

// Implementing interface method


@Override
public void overrideMethod(String str)
{
System.out.println(str);
}
}

Output
Hello, New Static Method Here
Hello, Override Method here

Java program to demonstrate scope of static method in Interface.

• In this program, the scope of the static method definition is within the interface only.
• If same name method is implemented in the implementation class, then that method
becomes a static member of that respective class.

interface PrintDemo {
// Static Method
static void hello()
{
System.out.println("Called from Interface PrintDemo");
}
}
public class InterfaceDemo implements PrintDemo {
public static void main(String[] args)
{
// Call Interface method as Interface
// name is preceding with method
PrintDemo.hello();
// Call Class static method
hello();
}
// Class Static method is defined
static void hello()
{
System.out.println("Called from Class");
}
}

Output
Called from Interface PrintDemo
Called from Class

26
22CS202 – Java Programming (Theory Course with Lab Component)

2.7 Packages in Java

Package is a collection of predefine classes and interface. Java provides different type of inbuilt
packages for different task. Programmer can also create own packages. All Java predefine
classes are distributed into several different package.
Advantage of Java Package
• Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
• Java package provides access protection
• Java package removes naming collision

Some packages are

lang Package: Lang stands for language. This package contains that class which are essential
for every java program.

E.g. String and System class

Lang is the default package of java which means it is optional to import Lang package in
program

io package: io stands for input/output. This package contains that class which are essential for
input and output. Some classes of input/output package are;

E.g. – DataInputStream, BufferReader, DataInputStreamReader

util package: util stands for utility package this package contains different type of classes
related to various task.

E.g.: Date, time, calendar, array, vector. Array List etc.

awt package (swing): awt stands for abstract windowing tool. With the help of this package,
we can create GUI interface. This package provides many GUI tools.

E.g.: Command button, choice, list, radio, etc.


awt contain a sub package name “even”.

27
22CS202 – Java Programming (Theory Course with Lab Component)

applet: with the help of applet function, we can create a java program which can be embedded
into HTML page by which web browser execute the java program. Web browser must be java
enabled.

Sql Package: sql stands for structure query language. This package provides a complete range
of classes which is needed for jdbc (java database connectivity). Some important classes of sql
package are:

E.g.: connection, ResultSet, PrepareStatement, etc.

Net package: net stands for networking. This package contains classes to implement or create
connection between two or more systems or if we want to implement client server approach
then. We can use the classes of net package.

E.g.: TCP/IP, Request, etc.

Types of packages

➢ Programmers can define their own packages to bundle group of classes/interfaces, etc.
It is a good practice to group related classes implemented, so that a programmer can
easily determine that the classes, interfaces, enumerations, and annotations are related.
➢ Since the package creates a new namespace there is no chance for any name conflicts
with names in other packages. Using packages, it is easier to provide access control and
it is also easier to locate the related classes.

Built-in Packages

These packages consist of many classes which are a part of Java API. Some of the commonly
used built-in packages are:
1. java.lang: Contains language support classes(e.g. classed which defines primitive data
types, math operations). This package is automatically imported.
2. java.io: Contains classed for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support : for Date / Time operations.
4. java.applet: Contains classes for creating Applets.
5. java.awt: Contain classes for implementing the components for graphical user
interfaces (like button, menus etc.).
6. java.net: Contain classes for supporting networking operations.

Syntax of Import package

import [package name].*; // (all class)

28
22CS202 – Java Programming (Theory Course with Lab Component)

import [package name].[class name];//(Single class)

Creating a package
➢ While creating a package, name for the package is chosen and included in
the package statement at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that are included in the package.
➢ The package statement should be the first line in the source file.
➢ There can be only one package statement in each source file, and it applies to all types
in the file. If a package statement is not used then the class, interfaces, enumerations,
and annotation types will be placed in the current default package.

Steps to create package in Java


➢ First create a directory within name of package.
➢ Create a java file in newly created directory.
➢ In this java file you must specify the package name with the help of package keyword.
➢ Save this file with same name of public class
➢ Note: only one class in a program can declare as public.
➢ Now you can use this package in your program.

Example 1

Package Pack1
public class Demo
{
public void Show()
{
System.out.print(“Package called”);
}
}

➢ To compile the Java programs with package statements, you must use -d option as
shown below.
➢ javac -d Destination_folder file_name.java
➢ Then a folder with the given package name is created in the specified destination, and
the compiled class files will be placed in that folder.
➢ Now a package/folder with the package name will be created in the current directory
and these class files will be placed in it.

Compiling Java package

29
22CS202 – Java Programming (Theory Course with Lab Component)

Syntax
javac -d directory java_filename

Example to Compile:
javac -d Pack1 Demo.java

How to run java package program

Example to Execute:
java Pack1.Demo

After that use this package in your program

import Pack1.*;
class A
{
public static void main(String …args)
{
Demo ob1= new demo();
ob1.Show();
}
}

Advantage of Java Package


➢ Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
➢ Java package provides access protection.
➢ Java package removes naming collision.

Example 2
Arithmetic operations using packages
package arithmetic;
public class MyMath
{
public intadd(intx,int y)
{
return x+y;
}
public intsub(intx,int y)
{
return x-y;
}
public intmul(intx,int y)
{
return x*y;
}
public double div(intx,int y)
{
return (double)x/y;
}

30
22CS202 – Java Programming (Theory Course with Lab Component)

public intmod(intx,int y)
{
return x%y;
}
}

Note: Move to parent directory, write the following file and execute it.
import arithmetic.*;
class Test
{
public static void main(String as[])
{
MyMath m=new MyMath();
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
}
}

/* Output: */
13
3
40
1.6
3

Import packages in Java

Java has an import statement that allows you to import an entire package (as in earlier
examples), or use only certain classes and interfaces defined in the package.

The general form of import statement is:

import package.name.ClassName; // To import a certain class only


import package.name.* // To import the whole package

For example,

import java.util.Date; // imports only Date class


import java.io.*; // imports everything inside java.io package
The import statement is optional in Java.

If you want to use class/interface from a certain package, you can also use its fully
qualified name, which includes its full package hierarchy.

Here is an example to import a package using the import statement.

import java.util.Date;

31
22CS202 – Java Programming (Theory Course with Lab Component)

class MyClass implements Date {


// body
}
The same task can be done using the fully qualified name as follows:

class MyClass implements java.util.Date {


//body
}

Importing specific class


Using an importing statement, we can import a specific class. The following syntax is
employed to import a specific class.

Syntax
import packageName.ClassName;

Let us look at an import statement to import a built-in package and Scanner class.

Example
package myPackage;
import java.util.Scanner;
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
}
}

In the above code, the class ImportingExample belongs to myPackage package, and it
also importing a class called Scanner from java.util package.

Importing all the classes


Using an importing statement, we can import all the classes of a package. To import
all the classes of the package, we use * symbol. The following syntax is employed to import
all the classes of a package.

Syntax
import packageName.*;

Let us look at an import statement to import a built-in package.

Example
package myPackage;
import java.util.*;
public class ImportingExample
{

32
22CS202 – Java Programming (Theory Course with Lab Component)

public static void main(String[] args)


{
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
Random rand = new Random();
int num = rand.nextInt(100);
System.out.println("Randomly generated number " + num);
}
}

In the above code, the class ImportingExample belongs to myPackage package, and it
also importing all the classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc.
from the java.util package.

Using Static Import

• Static import is a feature introduced in Java programming language (versions 5 and


above) that allows members ( fields and methods ) defined in a class as public static to
be used in Java code without specifying the class in which the field is defined.
• Following program demonstrates static import:
// Note static keyword after import.
import static java.lang.System.*;
class StaticImportDemo
{
public static void main(String args[])
{
// We don't need to use 'System.out'
// as imported using static.
out.println("GeeksforGeeks");
}
}

Handling name conflicts


import java.util.*;
import java.sql.*;
//And then use Date class, then we will get a compile-time error:
Date today ; //ERROR-- java.util.Date or java.sql.Date?

The compiler will not be able to figure out which Date class do we want. This problem can be
solved by using a specific import statement:

import java.util.Date;
import java.sql.*;

If we need both Date classes then, we need to use a full package name every time we declare
a new object of that class.

java.util.Date deadLine = new java.util.Date();


java.sql.Date today = new java.sql.Date();

33
22CS202 – Java Programming (Theory Course with Lab Component)

Packages and member access

• The public members can be accessed everywhere.


• The private members can be accessed only inside the same class.
• The protected members are accessible to every child class (same package or other
packages).
• The default members are accessible within the same package but not outside the
package.

Access Modifiers

• Modifier 1: Public Access Modifiers


• If a class is declared as public then we can access that class from anywhere.
• Modifier 2: Package (Default) Access Modifier
• A class or method or variable declare without any access modifier then is
considered that it has a package(default)access modifier.
• The default modifier act as public within the same package and acts as private
outside the package.
• If a class is declared as default then we can access that class only within the
current package i.e., from the outside package we cannot access it. Hence, the
default access modifier is also known as the package–level access modifier.
• A similar rule also applies for variables and methods in java.

Important points

• Every class is part of some package.


• If no package is specified, the classes in the file goes into a special unnamed package
(the same unnamed package for all files).
• All classes/interfaces in a file are part of the same package. Multiple files can specify
the same package name.
• If package name is specified, the file must be in a subdirectory called name (i.e., the
directory name must match the package name).
• We can access public classes in another (named) package using: package-name.class-
name.

2.8 Exceptions
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the

34
22CS202 – Java Programming (Theory Course with Lab Component)

program/Application terminates abnormally, which is not recommended, therefore, these


exceptions are to be handled.

Definitions:
• An exception is an abnormal condition that arises in a code sequence at run time.
• An exception is a runtime error.

Error vs Exception
Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.

Exception Handling in Java


Exception handling in java is one of the powerful mechanisms to handle the runtime
errors so that normal flow of the application can be maintained. Exception Handling is a
mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the
application.
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in program and there occurs an exception at statement
5, rest of the code will not be executed i.e., statement 6 to 10 will not run. If we perform
exception handling, rest of the statement will be executed.

Types of errors in Java


There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.

Unchecked Exception

35
22CS202 – Java Programming (Theory Course with Lab Component)

The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.

Common scenarios where exceptions may occur

Scenario where ArithmeticException occurs

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


int a=50/0; //ArithmeticException

Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs
an NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException

Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I


have a string variable that have characters, converting this variable into digit will occur
NumberFormatException.
String s=null;
System.out.println(s.length()); //NullPointerException

Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Exception Hierarchy

36
22CS202 – Java Programming (Theory Course with Lab Component)

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following
table describes each.

Keyword Description
try The "try" keyword is used to specify a block where we should place an exception
code. It means we cannot 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 cannot use catch block alone. It can be followed by 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 does not throw an exception. It is always used
with method signature.

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 statement in the try block, the rest of the block code will
not execute.
• So, it is recommended not to keep the code in try block that will not throw an exception.

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.

Syntax of java try-catch

try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}

37
22CS202 – Java Programming (Theory Course with Lab Component)

Example Program:
public class TryDemo
{
public static void main(String args[])
{
try
{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}

finally block
• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block
• Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Example

class TestFinallyBlock
{
public static void main(String args[])
{
Try
{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e)
{
System.out.println(e);
}
//executed regardless of exception occurred or not
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

38
22CS202 – Java Programming (Theory Course with Lab Component)

Output
5
finally block is always executed
rest of the code…

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. So, if you must perform
different tasks at the occurrence of different exceptions, use java multi-catch block.

Example

public class MultipleCatchBlock1


{
public static void main(String[] args)
{
try
{
inta[]=new int[5];
a[5]=30/0;
}

catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output
Arithmetic Exception occurs
rest of the code

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 statement in try block, context of that exception is
pushed onto the stack.

For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException
while the outer try block can handle the ArithemeticException (division by zero).

39
22CS202 – Java Programming (Theory Course with Lab Component)

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
}
....
Example
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);

40
22CS202 – Java Programming (Theory Course with Lab Component)

}
//inner try block 2
try{
inta[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output

going to divide by 0
java.lang.AritmeticException: / by zero
java.lang.ArrayIndexOutOfBoundException: Index 5 out of bounds for length 5
other statement
normal flow

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.

Syntax

throw new exception_class("error message");

Example

throw new IOException("sorry device error");

public class ThrowExample {


static void checkEligibilty(intstuage, intstuweight){
if(stuage<12 &&stuweight<40) {
throw new ArithmeticException("Student is not eligible for registration");
}

41
22CS202 – Java Programming (Theory Course with Lab Component)

else {
System.out.println("Student Entry is Valid!!");
}
}

public static void main(String args[]){


System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a nice day..");
}
}

Output

Welcome to the Registration process!!Exception in thread "main"


java.lang.ArithmeticException: Student is not eligible for registration
at beginnersbook.com.ThrowExample.checkEligibilty(ThrowExample.java:9)
at beginnersbook.com.ThrowExample.main(ThrowExample.java:18)

Java throws keyword


• The Java throws keyword is used to declare an exception.
• It gives an 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.

Syntax

return_typemethod_name() throws exception_class_name


{
//method code
}

Example

import java.io.IOException;
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
Try
{
n();

42
22CS202 – Java Programming (Theory Course with Lab Component)

}
catch(Exception e)
{
System.out.println("exception handled");
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

Output

exception handled
normal flow...

Types of Exception in Java


Below is the list of important built-in exceptions in Java
1. Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundException
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. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
11. RuntimeException
This represents any exception which occurs during runtime.

43
22CS202 – Java Programming (Theory Course with Lab Component)

12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the
size of the string

User Defined Exception

• User Defined Exception or custom exception is creating your own exception class and
throws that exception using ‘throw’ keyword. This can be done by extending the class
Exception.
• 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.

class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String toString(){
return ("Exception Number = "+a) ;
}
}

The keyword “throw” is used to create a new Exception and throw it to the catch block.

Example:

class InvalidAgeException extends Exception


{
// class representing custom exception
public InvalidAgeException (String str)
{
super(str);
// calling the constructor of parent Exception
}
}

44
22CS202 – Java Programming (Theory Course with Lab Component)

public class TestCustomException1


{ // class that uses custom exception InvalidAgeException
static void validate (int age) throws InvalidAgeException{
// method to check the age
if(age < 18){
throw new InvalidAgeException("age is not valid to vote");
// throw an object of user defined exception
}
else {
System.out.println("welcome to vote");
}
}
public static void main(String args[])
{ // main method
try
{
validate(13); // calling the method
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
System.out.println("Exception occured: " + ex);
// printing the message from InvalidAgeException object
}
System.out.println("rest of the code...");
}
}

45

You might also like