0% found this document useful (0 votes)
12 views

Unit-4 Inheritance , Packages and Exception Handling using java

The document outlines Unit-4 of the Principles of Programming Languages course, focusing on Inheritance, Packages, and Exception Handling in Java. It covers key concepts such as member access, super class references, method overriding, and exception management, along with practical examples. The content is structured to facilitate understanding of Java's object-oriented programming features and exception handling mechanisms.

Uploaded by

karan.ppjgk22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Unit-4 Inheritance , Packages and Exception Handling using java

The document outlines Unit-4 of the Principles of Programming Languages course, focusing on Inheritance, Packages, and Exception Handling in Java. It covers key concepts such as member access, super class references, method overriding, and exception management, along with practical examples. The content is structured to facilitate understanding of Java's object-oriented programming features and exception handling mechanisms.

Uploaded by

karan.ppjgk22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Sinhgad College of Engineering, Pune

Approved by AICTE New Delhi Recognized by Govt. of Maharashtra


Affiliated to Savitribai Phule Pune University
Accredited by NAAC with A+ Grade

Subject:- 210255: Principles of Programming Languages


Unit-4 Inheritance , Packages and Exception Handling using Java

Mr. AJIT M. KARANJKAR


Assistant. Professor.
Department of Computer Engineering,
Sinhgad College of Engineering Vadgaon Bk, Pune-041
Email:- [email protected]

09-04-2025 1
Contents:
• Inheritances: member access and inheritance, super class references, Using super,
multilevel hierarchy, constructor call sequence, method overriding, dynamic
method dispatch, abstract classes, Object class.
• Packages and Interfaces: defining a package, finding packages and
CLASSPATH, access protection, importing packages, interfaces (defining,
implementation, nesting, applying), variables in interfaces, extending interfaces,
instance of operator. fundamental, exception types, uncaught exceptions, try,
catch, throw, throws, finally, multiple catch clauses, nested try statements, built-in
exceptions, custom exceptions (creating your own exception sub classes).
• Managing I/O: Streams, Byte Streams and Character Streams, Predefined
Streams, Reading console Input, Writing Console Output, Print Writer class.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 2
Department Of Computer Engineering
UNIT-4
INHERITANCE, PACKAGES &
EXCEPTION HANDLING USING JAVA

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 3
Department Of Computer Engineering
4.1 INHERITANCES
4.1.1 Member access and inheritance.
4.1.2 Super class references
4.1.3 Using Super, Multilevel Hierarchy
4.1.4 Constructor call Sequence.
4.1.5 Method Overriding.
4.1.6 Dynamic Method Dispatch.
4.1.7 abstract class.
4.1.8 Object class
UNIT-IV Inheritance , Packages & Exception Handling Using Java
4
Department Of Computer Engineering
4.1 Inheritance in Java
Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of
another class.

• 4.1.1 Base Class & Derived Class In Inheritance:

Super Class(Parent): The class whose properties are inherited by sub class is called Base
Class or Super class.

Sub Class (Child):


The class that inherits properties from another class is called Sub class or Derived Class.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 5
Department Of Computer Engineering
4.1 Inheritance in Java

Fig. 1 Base class & Derived class

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 6
Department Of Computer Engineering
4.1 Inheritance in Java
Types of Inheritance:

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 7
Department Of Computer Engineering
4.1 Inheritance in Java
Single Inheritance:
class A
{ int a;
void setdata(int i)
{ a=i;
}
void display( )
{ System.out.println( "The value of A:"+a);
}
}
class B extends A
{
int b;
void getdata(int j)
{
b=j;
}
void show( )
{ System.out.println( "The value of B: "+b);
}
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 8
Department Of Computer Engineering
4.1 Inheritance in Java
void addition()
{ int c;
c=a+b;
System.out.println("The Value of C:"+c);
}
}
class Demo1
{
public static void main(String args[ ])
{
A obj1=new A();
B obj2=new B();
obj1.setdata(10);
obj2.getdata(20);
obj1.display();
obj2.show();
obj2.addition(); }
} Output: javac Demo1.java
java Demo1
The Value of A:10
The Value of B:20 UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 9
The Value of C:30 Department Of Computer Engineering
4.1.1 Member access and inheritance
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class.

We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.

There are four types of Java access modifiers:


• Public
• Private
• Protected
• Default

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 10
Department Of Computer Engineering
4.1.1 Member access and inheritance
• Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

• Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

• Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.

• Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 11
Department Of Computer Engineering
4.1.1 Member access and inheritance

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 12
Department Of Computer Engineering
4.1.2 Super class Reference
• A subclass (derived class ) can invoke the constructor method defined by the superclass
(Base class).

• Syntax:
super( );
or
super(parameter_list);

• To invoke the constructor of superclass , super( ) or super(parameter_list) statement


should appear in the first line of the subclass constructor.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 13
Department Of Computer Engineering
4.1.2 Super Class Reference
Example:
class A
{ int a;
A (int i)
{
a=i;
}
void display( )
{ System.out.println( "The value of A:"+a);
}
}
class B extends A
{
int b;
B(int i)
{
super(i);
this.b=i+10;
}
void show( )
{ System.out.println( "The value of B:UNIT-IV
"+b);Inheritance , Packages & Exception Handling Using Java
} 23-03-2023 Department Of Computer Engineering
14
4.1.2 Super class Reference
void mul()
{ int c;
c=a*b;
System.out.println("The Value of C:"+c);
}
}
class SuperclassDemo
{
public static void main(String args[ ])
{

B obj2=new B(20);//Note that the object of subclass is created only


obj2.display();
obj2.show();
obj2.mul();
}
} Output: javac SuperclassDemo.java
java SuperclassDemo
The Value of A:20
The Value of B:30
23-03-2023
The Value of C:600 UNIT-IV Inheritance , Packages & Exception Handling Using Java
15
Department Of Computer Engineering
4.1.3 Using Super
Super Keyword in Java
• The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
• Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

• Usage of Java super Keyword

super can be used to refer immediate parent class instance variable.

super can be used to invoke immediate parent class method.

super() can be used to invoke immediate parent class constructor.


UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 16
Department Of Computer Engineering
4.1.3 Using Super

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 17
Department Of Computer Engineering
4.1.3 Using Super
super is used to refer immediate parent class instance variable.
• We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.
Example:
class Animal{
String color="white";
}
class Dog extends Animal
{
String color="black";
void display()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
} 23-03-2023 UNIT-IV Inheritance , Packages & Exception Handling Using Java
Department Of Computer Engineering
18
4.1.3 Using Super
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.display();
}
}
Output:
black
white
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 19
Department Of Computer Engineering
4.1.3 Using Super
• super can be used to invoke parent class method
• The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class.
• Example:
class Animal
{ void eat()
{ System.out.println("eating...");
}
}
class Dog extends Animal
{ void eat()
{System.out.println("eating bread...");
}
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 20
Department Of Computer Engineering
4.1.3 Using Super
void bark()
{ System.out.println("barking...");
}
void work()
{ super.eat();
bark();
}
}
class SuperMethod
{ public static void main(String args[])
{
Dog d=new Dog();
d.work();
} UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 21
Department Of Computer Engineering
}
4.1.3 Using Super
• Output:
eating…
barking…

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 22
Department Of Computer Engineering
4.1.3 Using Super
• super is used to invoke parent class constructor.
• The super keyword can also be used to invoke the parent class constructor.
class A
{
A( )
{
System.out.println("Constructor of Class A");
}
}
class B extends A
{
B( )
{
super( );
System.out.println("Constructor of Class B");
}
} UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 23
Department Of Computer Engineering
4.1.3 Using Super
class supConst
{
public static void main(String[] args)
{
B obj=new B();
}
}
Output:
Constructor of Class A
Constructor of Class B

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 24
Department Of Computer Engineering
4.1.3 Multileval Hierarchy
• The multi-level inheritance includes the involvement of at least two or more than two
classes.

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

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 25
Department Of Computer Engineering
4.1.3 Multileval Hierarchy
import java.util.*;
class student
{
int roll;
String name;
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
void getdata( )
{
System.out.print("Enter a string: ");
name= sc.nextLine(); //reads string
System.out.println("Enter Roll No of Student");
roll=sc.nextInt();
}
void display()
{
System.out.println("***output***");
System.out.println("Roll No of Student:"+roll");
System.out.println("Name No of Student:"+name);
} 23-03-2023 UNIT-IV Inheritance , Packages & Exception Handling Using Java
26
} Department Of Computer Engineering
4.1.3 Multileval Hierarchy
System.out.println("Name No of Student:"+name);
}
}
class book extends student
{
float price;
String name;
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
void setdata()
{
System.out.print("Name of Book: ");
name=sc.next();
System.out.println("Enter Price of book");
price= sc.nextFloat(); //reads string
}
void show()
{

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 27
Department Of Computer Engineering
4.1.3 Multileval Hierarchy
System.out.println("Price of Book:"+price);
System.out.println("Name of Book:"+name);
}
}
class result extends book
{
float per;
String year;
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
void setdata1()
{
System.out.print(" Enter Year of Student ");
year=sc.next();
System.out.println("Enter Percentage:");
per= sc.nextFloat(); //reads string
}

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 28
Department Of Computer Engineering
4.1.3 Multileval Hierarchy

void show1()
{ System.out.println("Year of Student:"+year);
System.out.println("Percentage:"+per);
}
}
class Multiple
{
public static void main(String args[])
{
student obj1=new student();
book obj2=new book();
result obj3=new result();
obj1.getdata();
obj2.setdata();
obj3.setdata1();
obj1.display();
obj2.show();
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 29
Department Of Computer Engineering
4.1.3 Multileval Hierarchy
obj3.show1();
}
}
C:\JavaProg\Unit-4>javac Multiple.java
C:\JavaProg\Unit-4>java Multiple
Enter a string: karan
Enter Roll No of Student 102
Name of Book: Java
Enter Price of book 25.5
Enter Year of Student TE
Enter Percentage: 75.5
***output***
Roll No of Student:102
Name No of Student:karan
Price of Book:25.5
Name of Book:Java
Year of Student:TE
Percentage:75.5
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 30
Department Of Computer Engineering
4.1.4 Constructor Call Sequence:
• Normally a superclass constructor is called before the subclass’s constructor . This is called
constructor chaining.

• Thus the calling of constructor occurs from top to down.


Example:

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 31
Department Of Computer Engineering
4.1.4 Constructor Call Sequence:
class A
{
A()
{
System.out.println("Inside A's constructor.");
}
}

// Create a subclass by extending class A.

class B extends A
{
B()
{
System.out.println("Inside B's constructor.");
}
}

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 32
Department Of Computer Engineering
4.1.4 Constructor Call Sequence:
// Create another subclass by extending B.
class C extends B
{
C()
{
System.out.println("Inside C's constructor.");
}
}
class SeqConst
{
public static void main(String args[]) {
C c = new C();
}
}
Output:
Inside A's constructor.
Inside B's constructor.
Inside C's constructor.
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 33
Department Of Computer Engineering
4.1.5 Method Overriding:
• If derived class defines same function as defined in its base class, it is known as function
overriding.

• If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

• Rules for Java Method Overriding:

➢ The method must have the same name as in the parent class

➢ The method must have the same parameter as in the parent class.

➢ There must be an IS-A relationship (inheritance).

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 34
Department Of Computer Engineering
4.1.5 Method Overriding:
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike is running safely");
}
}
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 35
Department Of Computer Engineering
4.1.5 Method Overriding:
class methodover
{
public static void main(String args[])
{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 36
Department Of Computer Engineering
4.1.6 Dynamic Method Dispatch:
• The dynamic method dispatch is also called as runtime polymorphism.

• During the run time polymorphism a call to overridden method is resolved at run time.

• The Overridden method is called using the reference variable of a super class (or derived base
class).

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 37
Department Of Computer Engineering
4.1.7 Abstract Classes:
Abstraction in Java
• Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

• Another way, it shows only essential things to the user and hides the internal details.

• Example of abstract class

abstract class A
{

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 38
Department Of Computer Engineering
4.1.8 Object Class:
• In java there is a special class method Object. If no inheritance is specified for the classes
then all those classes are subclass of the object class.

• The Object class is the parent class of all the classes in java by default. In other words, it is
the topmost class of java.

• Object obj=getObject();

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 39
Department Of Computer Engineering
4.2 PACKAGES AND INTERFACES
4.2.1 Defining a package.
4.2.2 Finding Package and CLASSPATH.
4.2.3 access Protection.
4.2.4 Importing Packages.
4.2.5 Interfaces.
4.2.6 Variables in interfaces.
4.2.7 Extending interfaces.
4.2.8 Instance of Operator.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


40
Department Of Computer Engineering
4.2.1 Defining a Package:
• Package is defined using a keyword package.
• The Syntax for declaring the package is
package name_of_package

• This package is defined at the beginning of the program.


• Package in java can be categorized in two form, built-in package and user-defined package.

syntax
• javac -d directory javafilename

• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 41
Department Of Computer Engineering
4.2.1 Defining a Package:
• Java provides a large number of classes groped into different packages based on their
functionality.
• The six foundation Java packages are:
• java.lang
Contains classes for primitive types, strings, math functions, threads, and exception
• java.util
Contains classes such as vectors, hash tables, date etc.
• java.io
Stream classes for I/O
• java.awt
Classes for implementing GUI – windows, buttons, menus etc.
• java.net
Classes for networking
• java.applet
Classes for creating and implementing applets

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 42
Department Of Computer Engineering
4.2.1 Defining a Package:

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 43
Department Of Computer Engineering
4.2.1 Defining a Package:
• Selected or all classes in packages can be imported:

• Implicit in all programs: import java.lang.*;


• package statement(s) must appear first
• import package.class;
• import package.*;

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 44
Department Of Computer Engineering
4.2.1 Defining a Package:
• Example:
package mypack;
public class simple
{
public static void main(String args[])
{
System.out.println("Hello Students, How are u...");
}
}
Output: javac -d . simple.java
java mypack.simple
Hello Students, How are u..
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 45
Department Of Computer Engineering
4.2.2 Finding a Package:
• Create a folder name My_package.
• Create one class which contains two methods. We will store this class in a file named as
A.java
• This file will be stored in a folder My_package.
Java Program:[A.java]
package My_Package;
public class A
{
int a;
public void setdata(int n)
{
a=n;
}
public void display( )
{
System.out.println("The value of a is"+a);
}
UNIT-IV Inheritance , Packages & Exception Handling Using Java
} 23-03-2023
Department Of Computer Engineering
46
4.2.2 CLASSPATH:

• CLASSPATH: CLASSPATH is an environment variable which is used by Application


ClassLoader to locate and load the .class files.

• The CLASSPATH defines the path, to find third-party and user-defined classes that are not
extensions or part of Java platform.

• Include all the directories which contain. class files and JAR files when setting the
CLASSPATH.

• How to Set CLASSPATH in Windows Using Command Prompt

set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\jdk1.8\bin

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 47
Department Of Computer Engineering
4.2.3 Access Protection

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 48
Department Of Computer Engineering
4.2.4 Importing Packages:
• In java, the import keyword used to import built-in and user-defined packages.

• All standard classes in java are stored in named packages.

• The import statement can be written at the beginning of the java program using the keyword
import.

• Syntax
import package.name.ClassName; // To import a certain class only
import package.name.* // To import the whole package

• For Example:
import java.io.File
or
import java.io.*;

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 49
Department Of Computer Engineering
4.2.4 Importing Packages:
• The syntax of importing a package or class is :
// To import all classes of a package
import packagename.*;
// To import specific class of a package
import packagename.classname;
// To import all classes of a sub package
import packagename.subpackagename.*;
// To import specific class of a sub package
import packagename.subpackagename.classname;

• Example

import mypack.*;
import mypack.MyFirstPackageProgram;
import java.util.*;

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 50
Department Of Computer Engineering
4.2.4 Importing Packages:
package mypack;

public class MyFirstPackageProgram


{
public void printMessage()
{
System.out.println("Inside printMessage method");
}
}

Another package:
package testpack;
import mypack.MyFirstPackageProgram;
// To import all classes of mypack package
// import mypack.*;

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 51
Department Of Computer Engineering
4.2.4 Importing Packages:
class PackageImportProgram
{
public static void main(String args [])
{
System.out.println("package import demo");
MyFirstPackageProgram mfp = new MyFirstPackageProgram();
mfp.printMessage();
}
}

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 52
Department Of Computer Engineering
4.2.5 Interface:
• An interface is a reference type in Java.

• It is similar to class. It is a collection of abstract methods.

• A class implements an interface, thereby inheriting the abstract methods of the interface.

Syntax:
interface <interface_name>
{

// declare constant fields


// declare methods that abstract
// by default.
}

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 53
Department Of Computer Engineering
4.2.5 Interface:
Example:
interface printable
{
void print();
}
class A7 implements printable
{
public void print(){System.out.println("Hello");
}

public static void main(String args[])


{
A7 obj = new A7();
obj.print();
}
}
Output:Hello
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 54
Department Of Computer Engineering
4.2.5 Interface:

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 55
Department Of Computer Engineering
4.2.6 Variable in Interfaces
• The variables can be assigned with some values within the interface.

• They are implicitly final and static.

• The interface contains the static final variables.

• The variables defined in an interface can not be modified by the class that implements the
interface, but it may use as it defined in the interface.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 56
Department Of Computer Engineering
4.2.6 Variable in Interfaces
• Example
interface printable{
int a=10;
}
public class A6 implements printable
{
public void print(){System.out.println("Value of a="+a);
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:
Value of a=10

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 57
Department Of Computer Engineering
4.2.7 Extending Interface
• In java, an interface can extend another interface. When an interface wants to extend
another interface, it uses the keyword extends.

• Interfaces can be extended similar to the classes. That means we can derive subclasses
from the main class using the keyword extend.

• Syntax:

interface interface_name2 extends interface_name1


{
------
------

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 58
Department Of Computer Engineering
4.2.7 Extending Interface
Program:
interface A
{
void get_A( );
}

interface B extends A
{
void get_B( );
}
// Class will implement methods from both interfaces
// As interface B is also extending interface A
class sample implements B
{
public void get_A( )
{
System.out.println("This is Class A");
} 23-03-2023
UNIT-IV Inheritance , Packages & Exception Handling Using Java
59
Department Of Computer Engineering
4.2.7 Extending Interface
public void get_B( )
{
System.out.println("This is Class B");
}}
public class extendprg
{
public static void main(String[] args)
{
sample obj = new sample ();
obj.get_A( );
obj.get_B( );
}
}
Output: javac extendprg.java
java extendprg
This is Class A
This is Class B
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 60
Department Of Computer Engineering
4.2.7.1 Multiple Inheritance
• Multiple inheritance is a mechanism in which the child class inherits the properties from
more than one parent classes.

• Java Programming does not support multiple inheritance because it create ambiguity error
when the properties from both the parent classes are inherited in child class or derived class.

• But it is supported in case of interface because there is no ambiguity as implementation is


provided by the implementation class.
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 61
Department Of Computer Engineering
4.2.7.1 Multiple Inheritance
Example:
interface student
{
void display( );
}

interface subject
{
void show( );
}

class Result implements student , subject


{
public void display()
{
System.out.println("Student Name: Ram");
}
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 62
Department Of Computer Engineering
4.2.7.1 Multiple Inheritance
public void show()
{
System.out.println("Subject Name: Java");
}
public static void main(String args[])
{
Result obj=new Result();
obj.display( );
obj.show( );
}
}

Output:
javac Result.java
java Result
Student name: Ram
Subject name: Java
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 63
Department Of Computer Engineering
4.2.8 The Instance of Operator
• The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).

• Example:
class Animal
{

}
class instance extends Animal
{ //instance inherits Animal
public static void main(String args[])
{
instance d=new instance();
System.out.println(d instanceof Animal);//true
}
}
Output: true
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 64
Department Of Computer Engineering
4.3 EXCEPTION HANDLING
4.3.1 Fundamentals.
4.3.2 Exception Types
4.3.3 Uncaught Exception
4.3.4 try, catch, throw, throws and finally
4.3.5 Multiple Catches clauses.
4.3.6 Nested try Statement.
4.2.7 Built in Exception
4.2.8 Custom Exceptions.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


65
Department Of Computer Engineering
4.3.1 Fundamentals
• Exception in java is an indication of unusual event. Usually it indicates the error.

• Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
They form an interrelated subsystem in which the use of one implies the use of another.

• What is Exception Handling?

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


IOException, SQLException, RemoteException, etc.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 66
Department Of Computer Engineering
4.3.1 Fundamentals
• Example:
class JavaExceptionExample
{
public static void main(String args[])
{
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
} output:
ArithmeticException / by zero.
Rest of the code
23-03-2023
UNIT-IV Inheritance , Packages & Exception Handling Using Java
67
Department Of Computer Engineering
4.3.2 Exception Types
• In Java, exception is an event that occurs during the execution of a program and disrupts the
normal flow of the program's instructions. Bugs or errors that we don't want and restrict our
program's normal execution of code are referred to as exceptions. In this section, we will
focus on the types of exceptions in Java and the differences between the two.

• Exceptions can be categorized into two ways:


• Built-in Exceptions
• Checked Exception
• Unchecked Exception

• User-Defined Exceptions

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 68
Department Of Computer Engineering
4.3.2 Exception Types

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 69
Department Of Computer Engineering
4.3.3 Uncaught Exception

• The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.

• Java programming language has a very strong exception handling mechanism. It allow us to
handle the exception use the keywords like try, catch, finally, throw, and throws.

• When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception occurs
and terminates the thread.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 70
Department Of Computer Engineering
4.3.3 Uncaught Exception
import java.util.Scanner;
public class UncaughtExceptionExample
{ public static void main(String args[])
{ Scanner read=new Scanner(System.in);
System.out.println("Enter the Value of a and b");
int a=read.nextInt();
int b=read.nextInt();
int c=a/b;
System.out.println(+a+"/"+b+"="+c);
}
} output:

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 71
Department Of Computer Engineering
4.3.4 try, Catch, throw, throws and finally

• Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
• If an exception occurs at the particular statement in the try block, the rest of the block code
will not execute. So, it is recommended not to keep the code in try block that will not throw
an exception.

• Syntax of Java try-catch


try{
//code that may throw an exception
}catch(Exception_class_Name ref)
{
// exception is handled here.
} 23-03-2023 UNIT-IV Inheritance , Packages & Exception Handling Using Java
72
Department Of Computer Engineering
4.3.4 try, Catch, throw, throws and finally
• If any one statement in the try block generates exception then remaining statements are
skipped and the control is then transferred to the catch statement.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 73
Department Of Computer Engineering
4.3.4 try, Catch, throw, throws and finally
class RunErrorDemo
{ public static void main(String args[])
{ int a,b,c;
a=10;
b=0;
try
{ c=a/b; //Exception occurs because the element is divided by 0
}catch(ArithmeticException e)
{ System.out.println("\n Divide by Zero..");//Execption is handled using catch block.
}
System.out.println("\n The value of a:"+a);
System.out.println("\n The value of b:"+b);
}
}
Output:Divide by Zero..
The value of a:10
The value of b:0
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 74
Department Of Computer Engineering
4.3.4 try, Catch, throw, throws and finally

• Using throws:
• The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception.
• When a method want to throw an exception then keyword throws is used.

• Syntax of Java throws


return_type method_name() throws exception_class_name
{
//method code
}

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 75
Department Of Computer Engineering
4.3.4 try, Catch, throw, throws and finally
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();
}catch(Exception e)
{System.out.println("exception handled");
}
} UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 76
Department Of Computer Engineering
4.3.4 try, Catch, throw, throws and finally
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output: exception handled
normal flow...

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 77
Department Of Computer Engineering
4.3.4 try, Catch, throw, throws and finally

• Using finally.
• Sometimes because of exception of try block the execution gets break off. And due to some
important code may not get executed.

• This some important code (which comes after throwing off an exception) may not get
executed.

• The finally block provides the assurance of execution of some important code that must be
executed after the try block.

• finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 78
Department Of Computer Engineering
4.3.4 try, Catch, throw, throws and finally
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);
}

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 79
Department Of Computer Engineering
4.3.4 try, Catch, throw, throws and finally
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
5
finally block is always executed
rest of the code...

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 80
Department Of Computer Engineering
4.3.5 Multiple Catch Clauses
• A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler.

• It is not possible for the try block to throw a single exception always.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 81
Department Of Computer Engineering
4.3.5 Multiple Catch Clauses
public class MultipleCatchBlock1
{
public static void main(String[] args)
{
try{
int a[]=new int[5];
a[5]=35/0;
/*String s=null;
System.out.println(s.length());*/
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
23-03-2023 }
UNIT-IV Inheritance , Packages & Exception Handling Using Java
82
Department Of Computer Engineering
4.3.5 Multiple Catch Clauses
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 83
Department Of Computer Engineering
4.3.6 Nested Try Statements:
• 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.
Example:
class NestedTryDemo
{
public static void main(String args[])
{
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int ans=0;
try
{
ans=a/b;
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 84
Department Of Computer Engineering
4.3.6 Nested Try Statements:
System.out.println("The result is"+ans);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero..");
}
}
catch(NumberFormatException e)
{
System.out.println("Incorrect type of data");
}
}
}
Output: javac NestedTryDemo.java
java NestedTryDemo 20 10
The result is 2
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 85
Department Of Computer Engineering
4.3.7 Built in Exception:
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations.

Below is the list of important built-in exceptions in Java. Examples of Built-in Exception:

ArithmeticException
NullPointerException
IOException
IndexOutBoundsException
ArrayStoreException
NumberFormatException
Exception.
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 86
Department Of Computer Engineering
4.3.7 Built in Exception:
Arithmetic exception : It is thrown when an exceptional condition has occurred in an
arithmetic operation.
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
} catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
} Output:
Can't divide a number by 0
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 87
Department Of Computer Engineering
4.3.7 Built in Exception:
NullPointerException : This exception is raised when referring to the members of a null
object. Null represents nothing.
// Java program to demonstrate NullPointerException
class NullPointer_Demo {
public static void main(String args[])
{
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
} output:
NullPointerException
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 88
Department Of Computer Engineering
4.4 Managing I/O
4.4.1 Streams
4.4.2 Byte Streams and Character Streams
4.4.3 Predefined Streams
4.4.4 Reading Console Input
4.4.5 Writing Console Output
4.4.6 Print Writer Class

UNIT-IV Inheritance , Packages & Exception Handling Using Java


89
Department Of Computer Engineering
4.4.1 Streams:
A stream can be defined as a sequence of data.
There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.

Stream is basically a channel on which the data flow from sender to receiver.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 90
Department Of Computer Engineering
4.4.2 Byte Streams and Character Streams:
Byte Streams:
Java byte streams are used to perform input and output of 8-bit bytes.

Though there are many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream.

Character Streams:

Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode.

Though there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter.

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 91
Department Of Computer Engineering
4.4.2 Byte Streams and Character Streams:

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 92
Department Of Computer Engineering
4.4.3 Predefined Streams:
• Every language has some predefined streams for its users and Java is one of these languages.
• Three Java Predefined streams or standard streams are available in the java.lang.System
class.
• These are as follows:

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 93
Department Of Computer Engineering
4.4.4 Reading Console Input:
• In java input id taken using System.in For that we wrap System.in a BufferedReader object
to create character stream.
• Classes provided by Java to take console Input:
• There are three classes using which we can take console input:

• BufferedReader class
• Scanner class

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 94
Department Of Computer Engineering
4.4.4 Reading Console Input:
• BufferedReader class: The BufferReader class is part of the java.io package.
• It is the oldest method introduced in Java to take user input. It has been present in Java since
the very beginning.
import java.io.*;
class Readchar
{ public static void main(String args[]) throws IOException
{ BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
int count=0;
char ch;
System.out.println("\n Enter Five character ");
while(count<5)
{ ch=(char)obj.read();//reading single character.
System.out.println(ch);
count++;
}
}
} Output: hi
h 23-03-2023 UNIT-IV Inheritance , Packages & Exception Handling Using Java
95
Department Of Computer Engineering
i
4.4.4 Reading Console Input:
import java.io.*;
class ReadString
{
public static void main(String args[]) throws IOException
{
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
String s;
s=obj.readLine();//for reading the string.
while(!s.equals("end"))
{
System.out.println(s);
s=obj.readLine();
}
}
}
Output: hello
hello
end 23-03-2023 UNIT-IV Inheritance , Packages & Exception Handling Using Java
96
Department Of Computer Engineering
4.4.4 Reading Console Input:
• Java Scanner Class:
• The Scanner class also known as the utility scanner is part of java.util package. The Scanner
class is simpler and better than BufferedReader. It takes input in the console or the
command line.
• Example:
import java.util.*;
public class ScannerClassInput
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String");
String str = sc.nextLine();
System.out.println("The String is: " +str);
System.out.println("Enter an Integer");
int i = sc.nextInt();
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 97
Department Of Computer Engineering
4.4.4 Reading Console Input:
System.out.println("The Integer is: " +i);
System.out.println("Enter a Float value");
float f = sc.nextFloat();
System.out.println("The Float value is: " +f);
}
}
Output:
Enter a String:
Amit
Enter an Integer
101
Enter a Float value
10.5
The String is:Amit
The Integer is:101
The Float value is:10.5

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 98
Department Of Computer Engineering
4.4.5 Writing Console Output:
• In java, there are two methods to write console output. Using the 2 following methods, we
can write output data to the console.

• Using print() and println() methods


• Using write() method
• Let's explore the each method to write data with example.

• 1. Writing console output using print() and println() methods


• The PrintStream is a bult-in class that provides two methods print() and println() to write
console output. The print() and println() methods are the most widely used methods for
console output.

• Both print() and println() methods are used with System.out stream.
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 99
Department Of Computer Engineering
4.4.5 Writing Console Output:
class sample
{
public static void main(String args[ ])
{
System.out.println("Hello Student's");
}
}
Output: Hello Student’s

2. Writing console output using write( ) methods

The simple method used for writing the output on the console is write( ). Here is the syntax of
using write ( ) method.

Syntax
System.out.write( int b)

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 100
Department Of Computer Engineering
4.4.5 Writing Console Output:
public class WritingDemo
{
public static void main(String[] args)
{
int[] list = new int[26];

for(int i = 0; i < 26; i++) {


list[i] = i + 65;
}

for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
}
}

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 101
Department Of Computer Engineering
4.4.6 Print Write Class:
The System.out is used to write the contents of the console. Similarity the PrinterWriter class
is also useful in writing the contents to the console.

It is mostly recommended for debugging purpose.

The PrintWriter Class is one of the character based classes.

This class support print and println methods.

The writer object for PrintWriter class is created is as follows-

PrintWriter pw=new PrintWriter(System.out);

UNIT-IV Inheritance , Packages & Exception Handling Using Java


23-03-2023 102
Department Of Computer Engineering
4.4.6 Print Write Class:
import java.io.*;
public class PrintWriterDemo
{
public static void main(String[] args)
{
char c='A';
int val=100;
double d=1024.354;
PrintWriter pw=new PrintWriter(System.out);
pw.print(c);
pw.println( );//change the line
pw.print(val);
pw.println( );//change the line
pw.print(d);
pw.flush( );
}
}
UNIT-IV Inheritance , Packages & Exception Handling Using Java
23-03-2023 103
Department Of Computer Engineering

You might also like