
Class employee
{
float sal =
60000;
}
Class employee1 extends employee
{ float b=1500;
Float temp=sal + b;
public static void main(String args[])
{employee1 ob=new employee1();
System.out.println(“salary amount is “obj.sal);
System.out.println(Ëxtra bonus is “+ obj.temp);
}
}
Salary amount is 6000
Extra bonus
6500
Defining
sub class
A sub class is defined as follows
Class
subclassname extends superclassname
{
Variable declaration;
methods
declaration;
}
The keyword extends signifies that the
properties of the super class name are extended to the sub class name. The sub
class now contain its own variables and methods as well these of the super
class. This kind of situation occurs when we want to add some more properties
to an existing class without actually modifying it.
Multilevel
inheritance
A common requirement in object oriented
programming is the use of a derived
class as a super class, java supports this concept and uses it extensively in
building its class library
Import
java.io.*;
Class
A
{
int a =2;}
Class
B extends A
{int
b =3;
}
Class
C extends B
{
int c =4;
void
show()
{
System.out.println(a +b +c);
}
}
Public
class multilevel
{
C ob = new C();
Ob.show();
}
}
Hierarchical
inheritance
In hierarchical inheritance, one class
servers as a super class (base class) for more than one sub class, the class A
serves as a base class for the derived class B,C,D more than one sub class is
inherited from a single base class more than one derived class is created from
a single base class.
Hierarchical inheritance in java is one
of the types of inheritance in Java. Inheritance is one of the implementation
of an object oriented programming system. An inheritance is a mechanism in
which one class inherits or acquires all the attributes and behavior of the
other class. The class from which inherits the attributes and behaviors are
called parent or super or base class and the class which inherits the
attributes and behaviors are called child or derived class. The use of
inheritance in java is for the reusability of code.
Class
employee
{
float salary =40000;
}
Class
permanentemp extends employee
{
double hike = 0.5;
}
Class
temporaryemp extends employee
{
double hike =0.3;
}
public class herinheritance
{
Public
static void main(String args[])
{
Permanentemp
p =new permanentemp;
Temporaryemp
t = new temporaryemp;
System.out.println(“permanent
employee salary is “+p.salary);
System.out.println(“hike
for permanent employee salary is “+p.hike);
System.out.println(“temporary
employee salary is “+t.salary);
System.out.println(“hile
for temporary employee salary is “+t.hike);
}
}
Thread
A
thread is similar to a program that has a single flow of control. It has a
beginning, a body and an end, and executes command sequentially.
Creating
Thread
Creating thread in java is simple.
Threads are implemented in the form of objects that contain a method called
run(). The run() method is the heart and soul of any thread. It makes up the
entire body of a thread and is the only method in which the thread’s behavior
can be implemented.
We can make our class run-able as a
thread by extending the class java.lang.Thread. This gives us access to all the
thread methods directly.
1. Declare the class as
extending the thread class.
2. Implement the run method
that is responsible for executing the sequence of code that the thread will
execute.
3. Create a thread object and
call the start() method to initiate the thread execution.
Stopping a Thread
Whenever
we want to stop a thread from running further, we may do so by calling the
stop() method, like
aThread.Stop()
This
statement causes the thread to move to the dead state automatically when
it reaches the end of its method.
Blocking a Thread
A
thread can also be temporarily suspended or blocked from entering into the
run-able and subsequently running state by using either of the following thread
methods.
Sleep() blocked for specified time
Suspend() blocked until further orders
Wait() blocked until certain condition occurs
Life cycle of a Thread
During
the life time of a thread, there are many states it can occur. They include
1. New born state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Declaring
the class
The thread class can be extended as
follows
Class
mythread extends Thread
{
……………
}
Implementing
the run() method
The run() method has been inherited by
the class mythread. The basic implementation of run() will look like this
Public
void run()
{
……………
}
When we start the new thread java calls
the thread run() method , so it is the run() where all the action takes place
Starting
a new thread
To actually create and run an instance
of our thread class we must write the following
mythread
athread = new mythread;
mythread.start();
The first line instantiates a new object
of the class mythread. Note that this statement just creates the object. The
thread that will run this object is not yet running. The thread is in a new
born state.
The second line calls the start ()
method causing the thread to move into the run-able state. Then, the java runtime will schedule the
thread to run by invoking the run() method. Now, the thread is said to be in
the running state.
New
born state
When we create thread object, the thread
is born and is said to be in new born state. The thread is not yet scheduled
for running. At this state, we can do only one of the following things with it.
-
Schedule it for running using start() method
-
Kill it using stop() method
Run-able state
The run-able
state means that the thread is ready for execution and is waiting for the
availability of the processor.
Running
state
` Running means that the processor has
given its time to the thread for its execution.
Blocked
state
A thread is said to be blocked when it
is prevented from entering into the run-able state and subsequently the running
state. This happens when the thread is suspended, sleeping, or waiting in order
to satisfy certain requirements. A blocked thread is considered “not run-able”
but not dead and therefore fully qualified to run again.
Dead
state
Every thread has a life cycle. A running thread end its life when it has
completed executing its run() method. It is a natural death. However, we can
kill it by sending the stop message to it as any state thus causing a premature
death to it. A thread can be killed as soon as it is born, or while it is
running, or even when it is in “not run-able” (blocked condition).
Import
java.lang.*;
class
multi extends Thread
{
Public
void run()
{
System.out.println(“thread is running”);
}
Public
static void main (String args[])
{
multi t1=new multi();
t1.start();
}
}
Thread
exceptions
Whenever we call a thread method that is
likely to throw an exception, we have to supply an appropriate exception
handler to catch it, The catch statement may take one of the following forms
Catch(ThreadDeath
e)
{
//
killed thread
}
Catch
(InterruptedException e)
{
//
cannot handle it in the current state
}
Catch(IllegalArgumentException
e)
{
//
Illegal method argument
}
Catch(Exception
e)
{
Any
other
}
Managing
errors and Exceptions
Errors may broadly be classified into
two categories
-
Compile –time errors
-
Run time errors
All syntax errors will be detected
and displayed by the java compiler and therefore those errors are known as
compile time errors.
Most
of the compile-time errors are due to typing mistakes. The most common problems
are
-
Missing semicolon
-
Misspelling of identifiers and keywords
-
Missing double quotes in strings
-
Use of undeclared variables
-
In compatible types in assignments / initialization
-
Bad references to objects
-
Use of = in place of
== operators
Run
time errors
Sometimes, a program may compile
successfully creating the .class file but may not run properly. Such programs
may produce wrong results due to wrong logic or may terminate due to errors,
such as stack overflow.
Most
common run time errors are
-
Dividing an integer by zero
-
Accessing an element that is out of the bounds of an error
-
Trying to illegally change the state of a thread
-
Attempting to use a negative size for an array
-
Converting invalid string to number
Java uses a keyword try to preface a block of code that is
likely to cause an error condition and “throw” an exception.
Try
{
Statement // generate an exception
}
Catch (Exception type e)
{
Processes the
exception
}
The try block
can have one or more statements that could generate an exception. If anyone
statement generates an exception, the remaining statements in the block are
skipped and execution jumps to the catch block that is placed next to the try
block
Common
Java Exception
Exception
type cause of exception
ArithmeticException math errors such as division by zero
ArrayIndexOutofBoundsException bad array indexes
ArrayStoreException when a program tries to store
the
wrong type of data in an array
FileNotFoundException an attempt to access a non
Existent file.
IOException general I/O failures such as
Inability to read
from file
NullpointerException referencing null object
NumberForamatException conversion between strings
and number fails
OutofmemoryException When there’s not enough
Memory to allocate a new object
SecurityException When an applet tries to perform an
Action not
allowed by the browser’s
Security
setting.
StackoverflowException when the system runs out of
Stack space
Finally
block
The finally block follows a try block or
a catch block. A finally block of code always executes, irrespective of
occurrence of an exception
Using a finally block allows you to run any clean up type
statements that you want to execute
public
class error5
{
public static void main(String args[])
{
int a[] = new int[2];
try
{
System.out.println(“access elements three
“+a[3]);
}
Catch(ArrayIndexOutofBoundsException
e)
{
System.out.println(“Exception thrown”+e);
}
Finally
{
a[0] = 6;
System.out.println(“first
element value “+a[0]);
System.out.println(“The
finally statement is executed”);
}
}
}
Exceptions
can be categorized into two types
Unchecked
Exceptions: They are not checked at compile time but at run time. For example
Arithmetic Exception, NullpointerException etc.
Checked
Exceptions : They are checked at compile time for example IOException,
Interrupted Exceptions etc.
Throws
keyword
We use the throw’s keyword in the method
declaration to declare the type of exceptions that might occur within it.
Import
java.io.*;
Class
file1
{
Public
static void findfile() throws IOException
{
File newfile = new file (“test.txt”);
FileInputStream
stream=new FileInputStream(newfile);
Public
static void main(String args[])
{
{
Try
{ findfile();
}
Catch(IOException
e)
{
System.out.println(e);
}
}
}
When we run this program , if the file
test.txt does not exist, FileInputStream throws a file not found Exception which extends the IOException
class.
The findfile() method specifies that an
IOException can be thrown. The main() method calls this method and handles the
exception if it is thrown
Java
throw keyword
The java throw keyword is used to
explicitly throw a single exception
When an exception is thrown, the flow of
program execution transfers from the try block to the catch block we use the
throw keyword within the method.