0% found this document useful (0 votes)
20 views67 pages

Java Inheritance and Exception Handling Guide

The document provides an overview of key concepts in Java programming, focusing on inheritance, exception handling, and the use of abstract classes and interfaces. It explains the differences between classes, subclasses, and superclasses, as well as the importance of reusability and method overriding. Additionally, it covers exception handling mechanisms, including try-catch blocks, throwing exceptions, and the use of finally blocks to ensure resource management.

Uploaded by

ps7207295
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)
20 views67 pages

Java Inheritance and Exception Handling Guide

The document provides an overview of key concepts in Java programming, focusing on inheritance, exception handling, and the use of abstract classes and interfaces. It explains the differences between classes, subclasses, and superclasses, as well as the importance of reusability and method overriding. Additionally, it covers exception handling mechanisms, including try-catch blocks, throwing exceptions, and the use of finally blocks to ensure resource management.

Uploaded by

ps7207295
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

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.
Why multiple inheritance is not supported in
java?

● To reduce the complexity and simplify the language, multiple


inheritance is not supported in java.
● Consider a scenario where A, B, and C are three classes. The C
class inherits A and B classes. If A and B classes have the same
method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
● Since compile-time errors are better than runtime errors, Java
renders compile-time error if you inherit 2 classes. So whether
you have same method or different, there will be compile time
error.
class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were
public static void main(String args[]){
C obj=new C();
[Link]();//Now which msg() method would be invoked?
}
}
Output: Compile Time Error
Using ‘Super’
class Vehicle {

int maxSpeed = 120;

class Car extends Vehicle {

int maxSpeed = 180;

void display(){

[Link]("Maximum Speed: "+ [Link]);

class Test {

public static void main(String[] args)

Car small = new Car();

[Link]();

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

● Usage of Java Method Overriding


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

● 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).
class Vehicle{
void run(){[Link]("Vehicle is
running");
}
}
class Bike extends Vehicle{
public static void main(String args[]){
Bike obj = new Bike();
[Link]();
}
}
class Vehicle{
void run(){[Link]("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){[Link]("Bike is running
safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
[Link]();//calling method
}
}
Creating multilevel Hierarchy
● Inheritance involves an object acquiring the properties and
behaviour of another object. So basically, using inheritance
can extend the functionality of the class by creating a new
class that builds on the previous class by inheriting it.

● Multilevel inheritance is when a class inherits a class which


inherits another class. An example of this is class C inherits
class B and class B in turn inherits class A.
class A {
void funcA() {
[Link]("This is class A");
}
}
class B extends A {
void funcB() {
[Link]("This is class B");
}
}
class C extends B {
void funcC() {
[Link]("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
[Link]();
[Link]();
[Link]();
}
Using Abstact Class
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).

Abstraction is a process of hiding the implementation details


and showing only functionality to the user.

Points to Remember
● An abstract class must be declared with an abstract keyword.

● It can have abstract and non-abstract methods.

● It cannot be instantiated.

● It can have constructors and static methods also.

● It can have final methods which will force the subclass not to change

the body of the method.


Syntax:
abstract class A{}

Example:
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){[Link]("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
[Link]();
}
}
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by
end user
class Rectangle extends Shape{
void draw(){[Link]("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){[Link]("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1(); //In a real scenario, object is provided through
method, e.g., getShape() method
[Link]();
}
}
Using final with Inheritance

The keyword final has three uses. First, it can be used to


create the equivalent of a named constant. This use was
described in the preceding chapter. The other two uses of final
apply to inheritance. Both are examined here.

● Using final to Prevent Overriding:


● While method overriding is one of Java’s most powerful
features, there will be times when you will want to prevent it
from occurring. To disallow a method from being overridden,
specify final as a modifier at the start of its declaration.
Methods declared as final cannot be overridden.
Class A
{
Final void meth()
{ [Link](“This is the final Method”);}
}
Class B extends A{
Void meth(){[Link](“Illegal”);} //Error! Can’t
override
}
Packages and Interfaces

● A java package is a group of similar types of classes, interfaces and


sub-packages.

● Package in java can be categorized in two form, built-in package and


user-defined package.

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

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that


they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Defining a Package
● To create a package is quite easy: simply include a package command as
the
first statement in a Java source file.
● Any classes declared within that file will belong to the specified package.

● The package statement defines a name space in which classes are

stored. If you omit the package statement, the class names are put into
the default package, which has no name.
● Syntax:

● package pkg;

● More than one file can include the same package statement. The package

statement simply specifies to which package the classes defined in a file


belong. It does not exclude other classes in other files from being part of
that same package. Most real-world packages are spread across many
files.
● package pkg1[.pkg2[.pkg3]];
Using packagename.*

//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}

//save by [Link]
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Using [Link]
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}

//save by [Link]
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
Using fully qualified name

//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}

//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
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.

● Along with abstract methods, an interface may also contain


constants, default methods, static methods, and nested types.
Method bodies exist only for default methods and static methods.
● An interface is similar to a class in the following ways −

● An interface can contain any number of methods.


● An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
● The byte code of an interface appears in a .class file.
● Interfaces appear in packages, and their corresponding bytecode file
must be in a directory structure that matches the package name.
Example
interface printable{
void print();
}

class A6 implements printable{


public void print(){[Link]("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
[Link]();
}
}
interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){[Link]("drawing circle");}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
[Link]();
}
}
Exception Handling in Java
The Exception Handling in Java is one of the powerful
mechanism to handle the runtime errors so that normal
flow of the application can be maintained.

Advantage of Exception Handling

The core advantage of exception handling is to maintain


the normal flow of the application. An exception normally
disrupts the normal flow of the application that is why we
use exception handling.
Syntax:
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Example:1

public class Main {


public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]); // error!
}
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
}
}
}
Exception Types

● All exception types are subclasses of the built-in


class Throwable. Thus, Throwable is at the top of
the exception class hierarchy
● There is an important subclass of Exception, called

RuntimeException. Exceptions of this type are


automatically defined for the programs that you
write and include things such as division by zero
and invalid array indexing.
● Error, which defines exceptions that are

notexpected to be caught under normal


circumstances by your program.
Uncaught Exceptions
Before you learn how to handle exceptions in your program, it is
useful to see what happens when you don’t handle them. This small
program includes an expression that intentionally causes a
divide-by-zero error:
Displaying a Description of an Exception

Throwable overrides the toString( ) method (defined by


Object) so that it returns a string containing a description of
the exception. You can display this description in a println( )
statement by simply passing the exception as an argument.
Built in Exception
ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic
operation.
ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index.
The index is either negative or greater than or equal to the size of the array.
ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not
found
FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
IOException
It is thrown when an input-output operation failed or interrupted
InterruptedException
It is thrown when a thread is waiting, sleeping, or doing some processing, and
it is interrupted.
NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException
It is thrown when accessing a method which is not found.
NullPointerException
This exception is raised when referring to the members of a null object. Null
represents nothing
NumberFormatException
This exception is raised when a method could not convert a string into a
numeric format.
RuntimeException
This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either
negative or greater than the size of the string
Multiple catch Clauses

● In some cases, more than one exception could be raised by a single piece of
code. To handle this type of situation, you can specify two or more catch
clauses, each catching a different type of exception.
Nested try Statements
● The try statement can be nested. That is, a try
statement can be inside the block of another try. Each
time a try statement is entered, the context of that
exception is pushed on the stack.
● If an inner try statement does not have a catch handler
for a particular exception, the stack is unwound and the
next try statement’s catch handlers are inspected for a
match.
throw
● It is possible for your program to throw an exception explicitly, using
the throw statement.

● Syntax:
● throw ThrowableInstance;

● Here, ThrowableInstance must be an object of type Throwable or a


subclass of Throwable. Primitive types, such as int or char, as well as
non-Throwable classes, such as String and Object, cannot be used as
exceptions. There are two ways you can obtain a Throwable object:
using a parameter in a catch clause or creating one with the new
operator.
● The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed. The nearest enclosing
try block is inspected to see if it has a catch statement that matches
the type of exception.
Example
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
validate(13);
[Link]("rest of the code...");
}
}

//error
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
[Link]("rest of the code...");
}
catch(Exception e){[Link]([Link]());}
}
}
throws

● If a method is capable of causing an exception that it does not handle, it


must specify this behavior so that callers of the method can guard
themselves against that exception.
● A throws clause lists the types of exceptions that a method might throw.
This is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses. All other exceptions that a
method can throw must be declared in the throws clause. If they are not,
a compile-time error will result.
Example

import [Link].*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
[Link]();
}catch(Exception e){[Link]("exception handled");}

[Link]("normal flow...");
}
}
Finally

● Java finally block is a block that is used to execute


important code such as closing connection, stream etc.

● The finally block will execute when the try/catch block


leaves the execution, no matter what condition cause it.
It always executes whether the try block terminates
normally or terminates due to an exception. The main
purpose of finally block is to release the system
resources.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always
executed");}
[Link]("rest of the code...");
}
}
The Java Thread Model
● The Java run-time system depends on threads for many
things, and all the class libraries are designed with
multithreading in mind.
● The value of a multithreaded environment is best
understood in contrast to its counterpart. Single-threaded
systems use an approach called an event loop with
polling. In this model, a single thread of control runs in an
infinite loop, polling a single event queue to decide what to
do next.
● The benefit of Java’s multithreading is that the main
loop/polling mechanism is eliminated. One thread can
pause without stopping other parts of your program.
Thread Priorities

● Java assigns to each thread a priority that determines how that


thread should be treated with respect to the others. Thread
priorities are integer that specify the relative priority of one thread
to another.
● A thread’s priority is used to decide when to switch from one

running thread to the next. This is called a context switch.


● Rules:

● A thread can voluntarily relinquish control. This occurs when

explicitly yielding, sleeping, or when blocked. In this scenario, all


other threads are examined, and the highest-priority thread that
is ready to run is given the CPU.
• A thread can be preempted by a higher-priority thread. In this
case, a lower-priority thread that does not yield the processor is
simply preempted—no matter what it is doing—by a higher-priority
thread. Basically, as soon as a higher-priority thread wants to run,
it does. This is called preemptive multitasking.
Synchronization
● Because multithreading introduces an asynchronous behavior to your
programs, there must be a way for you to enforce synchronicity when you
need it.

● We must prevent one thread from writing data while another thread is in the
middle of reading it. For this purpose, Java implements an elegant twist on
an age-old model of interprocess synchronization: the monitor.
● The monitor is a control mechanism Once a thread enters a monitor, all
other threads must wait until that thread exits the monitor.
● Messaging
● After you divide your program into separate threads, you need to define
how they will communicate with each other. When programming with some
other languages, you must depend on the operating system to establish
communication between threads.
The Thread Class and the Runnable Interface

● Java’s multithreading system is built upon the Thread class, its methods, and
its companion interface, Runnable.
● To create a new thread, your program will either extend Thread or implement the
Runnable interface.
The Main Thread

When a Java program starts up, one thread begins running


immediately. This is usually called the main thread of your program,
because it is the one that is executed when your program begins. The
main thread is important for two reasons:
• It is the thread from which other “child” threads will be
spawned.
• Often, it must be the last thread to finish execution because it
performs various shutdown actions.
public class currThread
{
public static void main(String[] args) {
Thread t = [Link]();
[Link]("Current Thread"+ t);
[Link]("Shri");
[Link]("After the name change"+ t);
try
{
for (int n=5;n>0 ;n-- ) {
[Link](n);
[Link](10);
}
}
catch(InterruptedException e){[Link]("Main Thread
Interrupted");}
}
Creating a Thread

In the most general sense, you create a thread by instantiating an object of


type Thread. Java defines two ways in which this can be accomplished:
• You can implement the Runnable interface.
• You can extend the Thread class, itself.
The following two sections look at each method, in turn.

Implementing Runnable
● The easiest way to create a thread is to create a class that implements

the Runnable interface. Runnable abstracts a unit of executable code.


You can construct a thread on any object that implements Runnable.
● To implement Runnable, a class need only implement a single method

called run( ).
● public void run( )

● The run( ) establishes the entry point for another, concurrent thread of

execution within your program. This thread will end when run( ) returns.
class Multi3 implements Runnable{
public void run(){
[Link]("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}
}
Extending Thread Class

The second way to create a thread is to create a new class that extends
Thread, and then to create an instance of that class. The extending
class must override the run( ) method, which is the entry point for the
new thread. As before, a call to start( ) begins execution of the new
thread.
Example:
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
Creating Multiple Threads

class MultithreadingDemo extends Thread {


public void run()
{
try {
// Displaying the thread that is running
[Link](
"Thread " + [Link]().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
[Link]("Exception is caught");
}
}
}
Cont.....

public class Multithread {


public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
[Link]();
}
}
}
Using isAlive( ) and join( )
Two ways exist to determine whether a thread has finished.
First, you can
call isAlive( ) on the thread. This method is defined by Thread,
and its general
form is shown here:
final boolean isAlive( )

The isAlive( ) method returns true if the thread upon which it is


called is still
running. It returns false otherwise.
isAlive()
public class JavaIsAliveExp extends Thread
{
public void run()
{
try
{
[Link](300);
[Link]("is run() method isAlive "+[Link]().isAlive());
}
catch (InterruptedException ie) {
}
}
public static void main(String[] args)
{
JavaIsAliveExp t1 = new JavaIsAliveExp();
[Link]("before starting thread isAlive: "+[Link]());
[Link]();
[Link]("after starting thread isAlive: "+[Link]());
}
}
join()
class JnMethod extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
[Link](500);
}catch(Exception e){[Link](e);}
[Link](i);
}
}
public static void main(String args[]){
JnMethod t1=new JnMethod();
JnMethod t2=new JnMethod();
JnMethod t3=new JnMethod();
[Link]();
try{
[Link]();
}catch(Exception e){[Link](e);}

[Link]();
[Link]();
}
Thread Priorities
● Thread priorities are used by the thread scheduler to decide
when each thread
● should be allowed to run.
● The amount of CPU time that a thread gets often depends on
several factors besides its priority. (For example, how an
operating system implements multitasking can affect the
relative availability of CPU time.)
● A higher-priority thread can also preempt a lower-priority one.
● Threads of equal priority should get equal access to the CPU
● To set a thread’s priority, use the setPriority( ) method, which is
a member of Thread. This is its general form:
● final void setPriority(int level)
Level specifies the new priority setting for the calling
thread. The value of level must be within the range
MIN_PRIORITY and MAX_PRIORITY. Currently, these
values are 1 and 10, respectively. To return a thread to
default priority, specify NORM_PRIORITY, which is
currently 5. These priorities are defined as static final
variables within Thread.

You can obtain the current priority setting by calling the


getPriority( ) method of Thread, shown here:

final int getPriority( )


Thread Synchronization
When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at a
time. The process by which this is achieved is called synchronization.
Key to synchronization is the concept of the monitor. A monitor is an object
that is used as a mutually exclusive lock. Only one thread can own a monitor
at a given time. When a thread acquires a lock, it is said to have entered the
monitor.

Why use Synchronization


The synchronization is mainly used to

● To prevent thread interference.


● To prevent consistency problem.
Using Synchronized Methods

class callme
{
synchronized void call(String msg){
[Link]("["+msg);
try
{
[Link](1000);
}
catch(InterruptedException e)
{[Link]("Interrupted");}
[Link]("]");

}
}
Cont.........
class caller implements Runnable{ class sync{
String msg; public static void main(String[] args) {
callme target; callme target = new callme();
Thread t; caller ob1 = new caller(target,"Hello");
public caller(callme targ, String s) caller ob2 = new caller(target,"Synch");
{ caller ob3 = new caller(target,"world");
target=targ; [Link]();
msg = s; [Link]();
t= new Thread(this); [Link]();
} try{
public void run(){[Link](msg);} [Link]();
} [Link]();
[Link]();}
catch(InterruptedException e)
{[Link]("Interrupted");}
[Link]();
}
}

You might also like