Professional Documents
Culture Documents
5 INHERITANCE
Inheritance is one of the important concept of object oriented
programming because it allows the creation of hierarchical
classifications. Using inheritance, you can create a general class that
defines traits common to a set of related items. This class can then
be inherited by other, more specific classes, each adding those things
that are unique to it. In the terminology of Java, a class that is inherited
is called a superclass. The class that does the inheriting is called a
subclass. Therefore, a subclass is a specialized version of a superclass.
It inherits all of the instance variables and methods defined by the
superclass and adds its own, unique elements. Java supports 4
inheritances:
1. simple inheritance
2. hierarchical inheritance
3. multilevel inheritance
4. multiple inheritance ( indirectly with the help of interfaces )
INHERITANCE BASICS:
To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword.
// A simple example of inheritance.
// Create a superclass.
class A
{
int i, j;
void showij()
{ System.out.println(“i and j :”+ i +” “+ j); }
}
void sum()
{ System.out.println(”i+j+k:” + (i+j+k)); }
}
class Simplelnheritance
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();
superOb.i = 10;
superOb.j = 20;
System.out.println(”Contents of superOb:”);
superOb.showij();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println(”Contents of subOb:”);
subOb.showij();
subOb.showk();
System.out.println(“Sum of i, j and k in subOb:”);
subOb.sum();
}
}
USING SUPER:
Whenever a subclass needs to refer to its immediate superclass, it can
do so by use of the keyword super. super has two general forms. The
first calls the superclass constructor. The second is used to access a
member of the superclass that has been hidden by a member of a
subclass.
Super.member
The second form of super acts like a this keyword except that it refers
to the immediate super class of the sub class in which it is used. It is
mostly applicable to the situations in which the member names of the
sub class hides the members of the super class. The member can be
either a method or instance variable.
Ex:
class A
{
int i;
private:
int j;
A(int x, int y)
{ j = x;
i = y;
}
void display()
{
System.out.println(i);
System.out.println(j);
}
}
class B extends A
{
int a;
B(int x, int y, int z)
{
super(x, y);
I = z;
}
void display()
{
super.display();
System.out.println(a);
}
}
class Main
{
public static void main(String args[])
{
B b1 = new B(10,20,30);
b1.display();
}
}
IMPLEMENTING INTERFACES:
Interfaces are used as “superclasses” whose properties are inherited
by classes. It is therefore necessary to create a class that inherits the
given interface. This is done as follows:
class classname implements Interfacename
{
body of classname
}
Here the class classname “implements” the interface interfacename. A
more general form of implementation may look like this:
class classname extends superclass implements
interfacel,interface2
{
body of classname
}
This shows that a class can extend another class while implementing
interfaces.
When a class implements more than one interface, they are separated
by a comma.
Ex:
interface Area // Interface defined
{
final static
float pi = 3.14F;
float compute (float x, float y);
}
class Rectangle implements Area // Interface implemented
{
public float compute (float x, float y)
{ return (x*y); }
}
class Circle extends Rectangle, implements Area //multiple
inheritance
{
public float compute (float x, float y)
{ return (pi*x*y); }
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle ( );
Circle cir = new Circle( );
Area area;
area = rect;
System.out.println(”Area of Rectangle:“
+area.compute(lO,2O)):
area = cir;
System.out.println(”Area of Circle:”+ area.compute(lO,O);
}
}
The Output is as follows:
Area of Rectangle = 200
Area of Circle = 314
Any number of dissimilar classes can implement an interface. However,
to implement the methods, we need to refer to the class objects as
types of the interface rather than types of their respective classes.
Note that if a class that implements an interface does not implement
all the methods of the interface, then the class becomes an abstract
class and cannot be instantiated.
ACCESSING INTERFACE VARIABLES:
Interfaces can be used to declare a set of constants that can be used in
different classes. Since such interfaces do not contain methods, there
is no need to worry about implementing any methods. The constant
values will be available to any class that implements the interface. The
values can be used in any method, as part of any variable declaration,
or anywhere where we can use a final value. Example:
interface A
{
int m = 10;
int n = 50;
}
class B implements A
{
int x=m;
void methodB(int size)
{
......
if (size < n)
......
}
}
COMPILE-TIME ERRORS:
All syntax errors will be detected and displayed by the Java compiler
and therefore these errors are known as compile-time errors.
Whenever the compiler displays an error, it will not create the .class
file. It is therefore necessary that we fix all the errors before we can
successfully compile and run the program.
Most of the compile-time errors are due to typing mistakes.
Typographical errors are hard to find. We may have to check the code
word by word, or even character by character. The most common
problems are:
• Missing semicolons
• Missing (or mismatch of) brackets in classes and methods
• Misspelling of identifiers and keywords
• Missing double quotes in strings
• Use of undeclared variables
• Incompatible types in assignments / initialization
• Bad references to objects
• Use of = in place of = = operator
• And so on
Other errors we may encounter are related to directory paths. An error
such as
javac : command not found
means that we have not set the path correctly. We must ensure that
the path includes the directory where the Java executables are stored.
Errorl.java :7: ‘;‘ expected
System.out.println (“Hello Java!”)
^
1 error
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 array
• Trying to store a value into an array of an incompatible class or type
• Trying to cast an instance of a class to one of its subclasses
• Passing a parameter that is not in a valid range or value for a method
• Trying to illegally change the state of a thread
• Attempting to use a negative size for an array
• Using a null object reference as a legitimate object reference to
access a method or a variable
• Converting invalid string to a number
• Accessing a character that is out of bounds of a string
And many more.
Ex:
class Error2
{
public static void main(String args[])
{
int a = 10;
int b = 5;
int c = 5;
int x = a/ (b—c); // Division by zero
System.out.println(”x = “ + x);
int y = a/(b+c);
System.out.println(“y = “ + y);
}
}
output:
java.lang.ArithmeticException: / by zero
at Error2 .main (Error2 .java:1O)
When Java run-time tries to execute a division by zero, it generates an
error condition, which causes the program to stop after displaying an
appropriate message.
EXCEPTIONS:
An exception is a condition that is caused by a run-time error in the
program. When the Java interpreter encounters an error such as
dividing an integer by zero, it creates an exception object and throws
it(i.e., informs us that an error has occurred).
If the exception object is not caught and handled properly, the
interpreter will display an error message and will terminate the
program. If we want the program to continue with the execution of the
remaining code, then we should try to catch the exception object
thrown by the error condition and then display an appropriate message
for taking corrective actions. This task is known as exception handling.
The purpose of exception handling mechanism is to provide a means to
detect and report an “exceptional circumstance” so that appropriate
action can be taken. The mechanism suggests incorporation of a
separate error handling code that performs the following tasks:
1. Find the problem (Hit the exception).
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
The error handling code basically consists of two segments, one to
detect errors and to throw exceptions and the other to catch
exceptions and to take appropriate actions.
Java exception handling is managed via five keywords: try, catch,
throw, throws, finally. Program statements that you want to monitor for
exceptions are contained within a try block. If an exception occurs
within the try block, it is thrown. Your code can catch this exception
(using catch) and then throw it in some rational manner. System-
generated exceptions are automatically thrown by Java run-time
system. To manually throw an exception, use the keyword throw; Any
exception that is thrown out of a method must be specified as such by
a throws clause. Any code that absolutely must be executed before a
method returns is put in finally block.
This is the general form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionTypel exOb)
{
// exception handler for ExceptionTypel
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// . . . . . . . . .
finally
{
// block of code to be executed before try block ends
}
catch (ArithmeticException e)
{
System.out.println(”Division by zero”);
y = a / (b+c);
System.out.println (“y =”+y);
}
}
}
output:
Division by zero
y=1
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. When
an exception is thrown, each catch statement inspected in order, and
the first one whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and
execution continues after the try/catch block. The following example
traps two different exception types:
Ex:
class Multicatch
{
public static void maln(String args[])
{
try
{
int a = args.length;
System.out.println(“a = “+ a);
int b = 42 / a;
int c[ ] = { 1 };
c[42] = 99;
}
catch (ArithmeticException e)
{
System.out.println(“Divide by 0: “+ e);
}
catch (ArraylndexOutOfBoundsException e)
{
System.out.println(“Arrayindexoutofbound: “+ e);
}
THROW:
It is possible for your program to throw an exception explicitly, using
the throw statement. The general form of throw is shown here:
throw Throwableinstance;
Throwableinstance must be an object of type Throwable or a subclass
of Throwable. Simple 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 into 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 the exception. If it does find a match, control is transferred
to that statement. If not, then the next enclosing try statement is
inspected, and so on. If no matching catch is found, then the default
exception handler halts the program and prints the stack trace.
Class DemoThrow
{
static void demoproc()
{
try
{
throw new NullPointerException(”demo”);
}
catch(NullPointerException e)
{
System.out.println(“Caught inside demoproc.”);
throw e; // rethrow the exception
}
}
THROWS:
If a method is capable of causing an exception that it does not
handled, it must specify the behavior so that callers of the method can
guard themselves against that exception. You do this by including a
throws clause in the method’s declaration. 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.
Syntax:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Exception-list is a comma-separated list of the exceptions that a
method can throw.
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println(“Inside throwOne”);
throw new IllegalAccessException(”demo”);
}
public static void main(String args[])
{
try {
throwOne ();
}
catch (IllegalAccessException e)
{
System.out.println(“Caught” +e);
}
output:
inside throwOne
caught java.lang.IllegalAccessException: demo
FINALLY:
When exceptions are thrown, execution in a method takes a rather
abrupt, nonlinear path that alters the normal flow through the method.
Depending upon how the method is coded, it is even possible for an
exception to cause the method to return prematurely. This could be a
problem in some methods. For example, if a method opens a file upon
entry and closes it upon exit, then you will not want the code that
closes the file to be bypassed by the exception-handling mechanism.
The finally keyword is designed to address this contingency.
finally creates a block of code that will be executed after a try/catch
block has completed and before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown. If
an exception is thrown, the finally block will execute even if no catch
statement matches the exception. Any time a method is about to
return to the caller from inside a try/catch block, via an uncaught
exception or an explicit return statement, the finally clause is also
executed just before the method returns. This can be useful for closing
file handles and freeing up any other resources that might have been
allocated at the beginning of a method with the intent of disposing of
them before returning. The finally clause is optional. However, each try
statement requires at least one catch or a finally clause.
class FinallyDemo
{
static void procA()
{
try
{
System.out.println(“inside procA”);
throw new RuhtimeException(”demo”);
}
finally
{
System.out .println(“procA’s finally”);
}
}
static void procB()
{
try
{
System.out.println(“inside procB”);
return;
}
finally
{
System.out.println(”procB’s finally”);
}
}
static void procC()
{
try
{
System.out.println(”inside procC”);
}
finally
{
System.out.println(”procC’s finally”);
}
}
public static void main(String args[])
{
try
{
procA ();
}
catch (Exception e)
{ System.out.println(”ExceptiOn caught”); }
procB ();
procC ();
}
}
output:
inside procA
procA’s finally
Exception caught
inside procB
procC’s finally
inside procC
procC’s finally
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-
zero.
ArrayIndexoutOfBoundException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of
an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a
method.
IllegalMonitorStateException Illegal monitor operation, such as
waiting on an unlocked thread.
IllegalStateException Environment or application is in
incorrect state.
IllegalThreadStateException Requested operation not
compatible with current thread
state.
IndexOutOfBoundsException Some type of index is out-of-
bounds.
NegativeArraySizeException Array created with a negative size.
NulPointerException valid use of a null reference.
NumberFormatException Invalid conversion of a string to a
numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBound Attempt to index outside the
bounds of a string
UnsupportedOperationException An unsupported operation was
encountered.
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that
does not implement the Cloneable
interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an
abstract class or interface.
InterruptedException One thread has been interrupted
by
another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Ex:
import java. lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x = 5, y = 1000;
try
{
float z = (float) x / (float) y;
if(z < 0.01)
throw new MyExcept±on(”Number is too
small”);
}
catch (MyException e)
{
System.out.println(”Caught my exception”);
System.out.println(e.getMessage( ) );
}
finally
{
System.out.println(”I am always here”);
}
}
}