Unit-4 Inheritance , Packages and Exception Handling using java
Unit-4 Inheritance , Packages and Exception Handling using java
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.
Super Class(Parent): The class whose properties are inherited by sub class is called Base
Class or Super class.
We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.
• 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.
• Syntax:
super( );
or
super(parameter_list);
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.
class B extends A
{
B()
{
System.out.println("Inside B's constructor.");
}
}
• If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
➢ The method must have the same name as in the parent class
➢ The method must have the same parameter as in the parent class.
• 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).
• Another way, it shows only essential things to the user and hides the internal details.
abstract class A
{
• 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();
syntax
• javac -d directory javafilename
• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
• 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.
• 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.*;
• Example
import mypack.*;
import mypack.MyFirstPackageProgram;
import java.util.*;
Another package:
package testpack;
import mypack.MyFirstPackageProgram;
// To import all classes of mypack package
// import mypack.*;
• A class implements an interface, thereby inheriting the abstract methods of the interface.
Syntax:
interface <interface_name>
{
• 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.
• Interfaces can be extended similar to the classes. That means we can derive subclasses
from the main class using the keyword extend.
• Syntax:
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.
interface subject
{
void 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.
• 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.
• User-Defined Exceptions
• 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.
• 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.
• 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.
• 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.
catch(NullPointerException e)
{
System.out.println(e);
}
• It is not possible for the try block to throw a single exception always.
• 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
Stream is basically a channel on which the data flow from sender to receiver.
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.
• BufferedReader class
• Scanner class
• 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
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)
for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
}
}