Unit-III
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by using the
extends keyword. To see how, let's begin with a short example. The following program creates a
superclass called A and a subclass called B. Notice how the keyword extends is used to create a
subclass of A. In Java, Inheritance means creating new classes based on existing ones. A
class that inherits the features(fields and methods) from another class can
reuse the methods and fields of that class. In addition, you can add new
A simple example of inheritance. fields and methods to your current class as well.
// Create a superclass.
class A {
int i, j;
void showij() {
[Link]("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
[Link]("k: " + k);
}
void sum() {
[Link]("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
1|Page
[Link]("Contents of superOb: ");
[Link]();
[Link]();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
[Link]("Contents of subOb: ");
[Link]();
[Link]();
[Link]();
[Link]("Sum of i, j and k in subOb:");
[Link]();
}
}
The output from this program is:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
Understanding Types of Inheritance: Single, Multilevel, Hierarchical Inheritance
Java supports the following four types of inheritance:
o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
2|Page
o Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes it is also known as simple
inheritance.
lass Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
[Link]("Total salary credited: "+[Link]);
[Link]("Bonus of six months: "+[Link]);
}
}
Output:
Total salary credited: 414408.0
Bonus of six months: 18000.0
o Multi-level Inheritance [Link]
3|Page
In multi-level inheritance, a class is derived from a class which is also derived from another
class is called multi-level inheritance.
//super class
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
[Link]("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
4|Page
{
[Link]("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
[Link]("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
[Link](0987);
[Link]();
[Link](78);
[Link]();
[Link](68.7);
[Link]();
}
}
Output:
registration number= 0987
5|Page
marks= 78.0
score= 68.7
[Link]
o Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called hierarchical inheritance.
//parent class
class Student
{
public void methodStudent()
{
[Link]("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
[Link]("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
6|Page
[Link]("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
[Link]("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
[Link]();
[Link]();
[Link]();
}
}
Output:
The method of the class Student invoked.
The method of the class Student invoked.
The method of the class Student invoked.
o Hybrid Inheritance
Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more
types of inheritance.
7|Page
//parent class
class GrandFather
{
public void show()
{
[Link]("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
[Link]("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
[Link]("I am son.");
}
8|Page
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
[Link]("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
[Link]();
}
}
Output:
I am daughter.
How does java support multiple inheritance?
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit
properties of more than one parent class. The problem occurs when there exist methods with
the same signature in both the superclasses and subclass. On calling the method, the compiler
cannot determine which class method to be called and even on calling which class method
gets the priority.
Multiple inheritance using interfaces
In case of multiple interfaces with the same default method. In the concrete class implementing
both interfaces, you can implement the common method and call both super methods. thus You
can achieve multiple inheritance in Java using interfaces.
interface MyInterface1{
public static int num = 100;
public default void display() {
9|Page
[Link]("display method of MyInterface1");
}
}
interface MyInterface2{
public static int num = 1000;
public default void display() {
[Link]("display method of MyInterface2");
}
}
public class InterfaceExample implements MyInterface1, MyInterface2{
public void display() {
[Link]("This is the implementation of the display method");
}
public void show() {
[Link]();
[Link]();
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
[Link]();
}
}
Output
display method of MyInterface1
display method of MyInterface2
using Super keyword
Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides a
solution to this problem. Whenever a subclass needs to refer to its immediate superclass, it can
do so by use of the keyword super.
10 | P a g e
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.
A subclass can call a constructor method defined by its superclass by use of the following form
of super:
super(parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the super class.
super() must always be the first statement executed inside a subclass' constructor.
To see how super( ) is used, consider this improved version of the BoxWeight( ) class:
// BoxWeight now uses super to initialize its Box attributes.
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}
Here, BoxWeight( ) calls super( ) with the parameters w, h, and d. This causes the Box( )
constructor to be called, which initializes width, height, and depth using these values.
BoxWeight no longer initializes these values itself. It only needs to initialize the value unique to
it: weight. This leaves Box free to make these values private if desired.
The second form of super acts somewhat like this, except that it always refers to the super class
of the subclass in which it is used. This usage has the following general form:
[Link]
Here, member can be either a method or an instance variable.
11 | P a g e
This second form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass. Consider this simple class
hierarchy:
// Using super to overcome name hiding.
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
[Link]("i in superclass: " + super.i);
[Link]("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
[Link]();
}
}
This program displays the following:
i in superclass: 1
i in subclass: 2
What is Method Overriding?
when a method in a subclass has the same name and type signature as a method in its superclass,
then the method in the subclass is said to override the method in the superclass. When an
12 | P a g e
overridden method is called from within a subclass, it will always refer to the version of that
method defined by the subclass.
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
[Link]("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
[Link]("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}
The output produced by this program is shown here:
13 | P a g e
k: 3
Understanding Dynamic method dispatch
Dynamic method dispatch is the mechanism by which a call to an overridden function is resolved
at run time, rather than compile time. Dynamic method dispatch is important because this is how
Java implements run-time polymorphism.
// Dynamic Method Dispatch
class A {
void callme() {
[Link]("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
[Link]("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
[Link]("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
[Link](); // calls A's version of callme
14 | P a g e
r = b; // r refers to a B object
[Link](); // calls B's version of callme
r = c; // r refers to a C object
[Link](); // calls C's version of callme
}
}
The output from the program is shown here:
Inside A's callme method
Inside B's callme method
Inside C's callme method
Working with Abstract class and Method
Any class that contains one or more abstract methods must also be declared abstract. To declare
a class abstract, you simply use the abstract keyword in front of the class keyword at the
beginning of the class declaration. There can be no objects of an abstract class. That is, an
abstract class cannot be directly instantiated with the new operator. Such objects would be
useless, because an abstract class is not fully defined. Also, you cannot declare abstract
constructors, or abstract static methods.
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
[Link]("This is a concrete method.");
}
}
class B extends A {
void callme() {
[Link]("B's implementation of callme.");
}
}
class AbstractDemo {
15 | P a g e
public static void main(String args[]) {
B b = new B();
[Link]();
[Link]();
}
}
Using final with inheritance
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.
The following fragment illustrates final:
class A {
final void meth() {
[Link]("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
[Link]("Illegal!");
}
}
Introduction to Package
The package is both a naming and a visibility control mechanism. You can define classes inside
a package that are not accessible by code outside that package. You can also define class
members that are only exposed to other members of the same package. This allows your classes
to have intimate knowledge of each other, but not expose that knowledge to the rest of the world.
Creating a Package
16 | P a g e
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.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package
called MyPackage.
package MyPackage;
The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system. For
example, a package declared as
package [Link];
Example:
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
17 | P a g e
if(bal<0)
[Link]("—> ");
[Link](name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
Call this file [Link], and put it in a directory called MyPack.
Understanding Access Protection
Java addresses four categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.
18 | P a g e
Importing packages
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.).
Example:
import [Link];
import [Link].*;
Introduction to Interfaces
Using the keyword interface, you can fully abstract a class' interface from its implementation.
That is, using interface, you can specify what a class must do, but not how it does it. Interfaces
are syntactically similar to classes, but they lack instance variables, and their methods are
declared without any body.
19 | P a g e
To implement an interface, a class must create the complete set of methods defined by the
interface. However, each class is free to determine the details of its own implementation. By
providing the interface keyword, Java allows you to fully utilize the "one interface, multiple
methods" aspect of polymorphism.
Defining an interface
An interface is defined much like a class. This is the general form of an interface:
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Here, access is either public or not used. When no access specifier is included, then
default access results, and the interface is only available to other members of the
package in which it is declared.
Here is an example of an interface definition. It declares a simple interface which
contains one method called callback( ) that takes a single integer parameter.
interface Callback
{
void callback(int param);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements clause in a class definition, and then
20 | P a g e
create the methods defined by the interface. The general form of a class that includes the
implements clause looks like this:
access class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
Here, access is either public or not used. If a class implements more than one interface,
the interfaces are separated with a comma. If a class implements two interfaces that
declare the same method, then the same method will be used by clients of either
interface.
class Client implements Callback
{
// Implement Callback's interface
public void callback(int p) {
[Link]("callback called with " + p);
}
}
How Interfaces are extended?
One interface can inherit another by use of the keyword extends. The syntax is the same as for
inheriting classes. When a class implements an interface that inherits another interface, it must
provide implementations for all methods defined within the interface inheritance chain.
Following is an example:
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() — it adds meth3().
interface B extends A {
void meth3();
21 | P a g e
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
[Link]("Implement meth1().");
}
public void meth2() {
[Link]("Implement meth2().");
}
public void meth3() {
[Link]("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
What is Exception?
An exception is an abnormal condition that arises in a code sequence at run time. In other words,
an exception is a runtime error. In computer languages that do not support exception handling,
errors must be checked and handled manually—typically through the use of error codes, and so
on.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
22 | P a g e
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
Understanding Exception Types
Built in Exceptions are
i. ArithmeticException: It is thrown when an exceptional condition has occurred in an
arithmetic operation.
ii. 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.
iii. ClassNotFoundException: This Exception is raised when we try to access a class
whose definition is not found
iv. FileNotFoundException: This Exception is raised when a file is not accessible or does
not open.
v. IOException: It is thrown when an input-output operation failed or interrupted
vi. InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
23 | P a g e
vii. NoSuchFieldException: It is thrown when a class does not contain the field (or
variable) specified
viii. NoSuchMethodException: It is thrown when accessing a method that is not found.
ix. NullPointerException: This exception is raised when referring to the members of a
null object. Null represents nothing
x. NumberFormatException: This exception is raised when a method could not convert
a string into a numeric format.
xi. RuntimeException: This represents an exception that occurs during runtime.
xii. StringIndexOutOfBoundsException: It is thrown by String class methods to indicate
that an index is either negative or greater than the size of the string
xiii. IllegalArgumentException : This exception will throw the error or error statement
when the method receives an argument which is not accurately fit to the given relation
or condition. It comes under the unchecked exception.
xiv. IllegalStateException : This exception will throw an error or error message when the
method is not accessed for the particular operation in the application. It comes under
the unchecked exception.
Introduction to Exception handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained. Exception Handling is a
mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
Working with try and catch
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero
24 | P a g e
error
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
Using 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.
class MultiCatch {
public static void main(String args[]) {
try {
int a = [Link];
[Link]("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
[Link]("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
[Link]("Array index oob: " + e);
}
[Link]("After try/catch blocks.");
}
}
Working with Finally, Throw and throws
25 | P a g 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;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
[Link]("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
[Link]("Recaught: " + e);
}
}
}
Throws
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
26 | P a g e
exceptions that a method can throw must be declared in the throws clause. If they are
not, a compile-time error will result.
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Finally
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.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
[Link]("inside procA");
throw new RuntimeException("demo");
} finally {
[Link]("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
[Link]("inside procB");
return;
} finally {
[Link]("procB's finally");
27 | P a g e
}
}
// Execute a try block normally.
static
Understanding Built-in Exceptions
Inside the standard package [Link], Java defines several exception classes. A few have been
used by the preceding examples. The most general of these exceptions are subclasses of the
standard type RuntimeException. Since [Link] is implicitly imported into all Java programs,
most exceptions derived from RuntimeException are automatically available. Furthermore, they
need not be included in any method's throws list. In the language of Java, these are called
unchecked exceptions because the compiler does not check to see if a method handles or throws
these exceptions.
28 | P a g e
exceptions defined by [Link] that must be included in a method's throws list if that method
can generate one of these exceptions and does not handle it itself. These are called checked
exceptions.
Creating user defined Exceptions
The following example declares a new subclass of Exception and then uses that subclass to
signal an error condition in a method. It overrides the toString( ) method, allowing the
description of the exception to be displayed using println( ).
// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
29 | P a g e
[Link]("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
[Link]("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
[Link]("Caught " + e);
}
}
}
30 | P a g e