Block 2
Block 2
Block 2
Polymorphism
Introduction
Objectives
Inheritance Basics
Access Control
Multilevel Inheritance
Method Overriding
Abstract Classes
Polymorphism
Final Keyword
Summary
Solutions/Answers
Page Nos.
27
27
27
30
35
36
38
39
41
42
42
2.0 INTRODUCTION
In Object Oriented Programming, one of the major feature is reusability. You are
already introduced to the reusability concept in Unit 2 of Block1 of this course.
Reusability in Java is due to the inheritance. Inheritance describes the ability of one
class or object to possess characteristics and functionality of another class or object in
the hierarchy. Inheritance can be supported as run-time or compile-time or both.
Here we are discussing inheritance with the Java programming language, and in our
discussion we will generally refer to compile-time inheritance.
In this unit we will discuss importance of inheritance in programming, concept of
superclass and subclass, and access controls in Java programming language. You will
see through example programs how methods are overridden, and how methods of a
super class are accessed by subclass. You will also see how multilevel inheritance is
implemented, use of abstract classes, and demonstration of polymorphism with the
help of example program.
2.1 OBJECTIVES
After going through this unit you will be able to:
27
inheritance is used for extending the existing property of a class. In other words it can
be said that inheritance is from generalization- to-specialization. In this by using
general class, class with specific properties can be defined.
Now let us take the example of Employee class, which is declared as:
class BankAccount
{
data members
member functions
}
data members and member functions of BankAccount class are used to display
characteristics of Withdraw, Deposit, getBalance of objects of a BankAccount class.
Now suppose you want to define a SavingAccount class. In the SavingAccount class
definitely you will have basic characteristics of a Bankaccount class mentioned above.
In your SavingAccount class you can use the properties of BankAccount class,
without any modification in them. This use of properties of BankAccount class in
Saving Account class is called inheriting property of BankAccount class into
SavingAccount class.
To inherit a class into another class extends keyword is used. For example,
SavingAccount class will inherit BankAccount class as given below.
class SavingAccount extends BankAccount
{
data members
ember functions
}
In this example, SavingAccount declares that it inherits or extends BankAccount.
Now let us see what is superclass and subclass.
28
wagePerHour = wage;
numHoursPerWeek = hours;
attitude = att;
}
public double getProductivity()
{
return numHoursPerWeek*attitude;
}
public double getTeamProductivity()
{
return getProductivity();
}
public int WeekSalary()
{
return wagePerHour*numHoursPerWeek;
}
}
Inheritance and
Polymorphism
If you look closely you will observe that Employee class possesses the very basic
characteristics of an employee. So think quickly about different type of employees! Of
course you can think about employees with special characteristics, for example,
Manager Engineer, Machine-man etc. You are right Subclass of Employee, will have
properties of Employee class as well as some more properties.
For example, if you take a class Manager (Subclass of Employee class) class. The
Manager is a more specialized kind of Employee. An important point to note is that
Manager represents a relationship with Employee. A Manager is a particular type of
employee, and it has all the properties of Employee class plus some more property
specific to it. Manager overrides the team productivity method to add the work done
by the employees working under him/her and adds some new methods of its own
dealing with other properties, which reflect characteristics of typical Managers. For
example, annoying habits, taking employees under her/him, preparing report for
employees, etc.
public class Manager extends Employee
{
// subclass of Employee
public Manager(int wage, int hours, double att, Employee underling)
{
super(wage, hours, att); // chain to our superclass constructor
}
public double getTeamProductivity()
{
// Implementation here
}
public int askSalary()
{
// Implementation here
}
public void addUnderling(Employee anUnderling)
{
// Implementation here
}
public void removeUnderling(Employee anUnderling)
{
// Implementation here
}
29
In the incomplete program above you can see that how inheritance is supporting in
cremental development. Basically in the above program (this program is incomplete,
you can write code to complete it) an attempt has been made to introduce a new code,
without causing bugs in the existing code.
Specifier
class
subclass
package
world
Private
Protected
Public
X
X
X
X*
X
X
X
Package
The first column indicates whether the class itself has access to the members defined
by the access specifier. As you can see, a class always has access to its own members.
The second column indicates whether subclasses of the class (regardless of which
package they are in) have access to the member.
The third column indicates whether classes in the same package as the class
(regardless of their parentage) have access to the member.
The fourth column indicates whether all classes have to the member.
30
Note that the protected/subclass intersection has an *. This particular case has a
special association with inheritance implementation. You will see in the next section
of this unit how protected specifier is used in inheritance. Package will cover in the
next unit of this Block.
1)
What is the advantage of inheritance? How can a class inherit the properties of
any other class in Java?
Inheritance and
Polymorphism
2)
3)
private
Private is the most restrictive access level. A private member is accessible only to the
class in which it is defined. You should use this access to declare members that you
are going to use within the class only. This includes variables that contain information
if it is accessed by an outsider could put the object in an inconsistent state, or
methods, if invoked by an outsider, could jeopardize the state of the object or the
program in which it is running. You can see private members like secrets you never
tell anybody.
To declare a private member, use the private keyword in its declaration. The following
class contains one private member variable and one private method:
class First
{
private int MyPrivate; // private data member
private void privateMethod() // private member function
{
System.out.println("Inside privateMethod");
}
}
Objects of class First can access or modify the MyPrivate variable and can invoke
privateMethod.Objects of other than class First cannot access or modify MyPrivate
variable and cannot invoke privateMethod . For example, the Second class defined
here:
class Second {
void accessMethod() {
First a = new First();
a. MyPrivate = 51;
// illegal
a.privateMethod();
// illegal
}
}
31
cannot access the MyPrivate variable or invoke privateMethod of the object of First.
If you are attempting to access a method to which it does not have access in your
program, you will see a compiler error like this:
Second.java:12: No method matching privateMethod()
found in class First.
a.privateMethod();
// illegal
1 error
One very interesting question can be asked, whether one object of class First can
access the private members of another object of class First. The answer to this
question is given by the following example. Suppose the First class contained an
instance method that compared the current First object (this) to another object based
on their iamprivate variables:
class Alpha
{
private int MyPrivate;
boolean isEqualTo (First anotherObject)
{
if (this. MyPrivate == anotherobject. MyPrivate)
return true;
else
return false;
}
}
This is perfectly legal. Objects of the same type have access to one anothers private
members. This is because access restrictions apply at the class or type level (all
instances of a class) rather than at the object level.
Now let us discuss protected specifier.
protected
Protected specifiers allows the class itself, subclasses, and all classes in the same
package to access the members. You should use the protected access level for those
data members or member functions of a class, which you can be accessed by
subclasses of that class, but not unrelated classes. You can see protected members as
family secretsyou dont mind if the whole family knows, and even a few trusted
friends but you wouldnt want any outsiders to know. A member can be declared
protected using keyword protected.
public class Student
{
protected int age;
public String name;
protected void protectedMethod()
{
System.out.println("protectedMethod");
}
}
You will see the use of protected specifier in programs discussed in next sections of
this block.
public
32
This is the easiest access specifier. Any class, in any package, can access the public
members of a classs. Declare public members only if you want to provide access to a
member by every class. In other words you can say if access to a member by outsider
cannot produce undesirable results the member may be declared public.
To declare a public member, use the keyword public. For example,
Inheritance and
Polymorphism
33
String name;
String address;
int age;
Student( String a, String b, int c)
{
name = a;
address = b;
age = c;
}
void display( )
{
System.out.println("*** Student Information ***");
Sstem.out.println("Name : "+name+"\n"+"Address:"+address+"\n"+"Age:"+age);
}
}
class PG_Student extends Student
{
int age;
int percentage;
String course;
PG_Student(String a, String b, String c, int d , int e)
{
super(a,b,d);
course = c;
percentage = e;
age = super.age;
}
void display()
{
super.display();
System.out.println("Course:"+course);
}
}
class Test_Student
{
public static void main(String[] args)
{
Student std1 = new Student("Mr. Amit Kumar" , "B-34/2 Saket J Block",23);
PG_Student pgstd1 = new PG_Student("Mr.Ramjeet ", "241- Near Fast Lane Road
Raipur" ,"MCA", 23, 80);
std1.display();
pgstd1.display();
}
}
Output:
*** Student Information ***
Name : Mr. Amit Kumar
Address:B-34/2 Saket J Block
Age:23
*** Student Information ***
Name : Mr.Ramjeet
Address:241- Near Fast Lane Road Raipur
Age:23
Course:MCA
34
In the above program PG_Student class is derived from Student class. PG_Student
class constructor has called constructor of Student class. One interesting point to note
in this program is that both Student and PG_Student classes have variable named age.
When PG_Student class will inherit class Student, member data age of Student class
will be hidden by the member data age of PG_Student class. To access member data
age of Student class in PG_Student class, super.age is used. Whenever any member
of a superclass have the same name of the member of subclass, it has to be accessed
by using super keyword prefix to it.
Inheritance and
Polymorphism
35
The following example program shows how member function area () of the class
Figure is overridden in subclasses Rectangle and Square.
36
class Figure
{
double sidea;
double sideb;
Figure(double a, double b)
{
sidea = a;
sideb = b;
}
Figure(double a)
{
sidea = a;
sideb = a;
}
double area( )
{
System.out.println("Area inside figure is Undefined.");
return 0;
}
}
class Rectangle extends Figure
{
Rectangle( double a , double b)
{
super ( a, b);
}
double area ( )
{
System.out.println("The Area of Rectangle:");
return sidea*sideb;
}
}
class Squre extends Figure
{
Squre( double a )
{
Inheritance and
Polymorphism
super (a);
}
double area( )
{
System.out.println("Area of Squre: ");
return sidea*sidea;
}
}
class Area_Overrid
{
public static void main(String[] args)
{
Figure f = new Figure(20.9, 67.9);
Rectangle r = new Rectangle( 34.2, 56.3);
Squre s = new Squre( 23.1);
System.out.println("***** Welcome to Override Demo ******");
f.area();
System.out.println(" "+r.area());
System.out.println(" "+s.area());
}
}
Output:
***** Welcome to Override Demo ******
Area inside figure is Undefined.
The Area of Rectangle:
1925.46
Area of Squre:
533.61
In most of the object oriented programming languages like C++ and Java, a reference
parent class object can be used as reference to the objects of derived classes. In the
above program to show overriding feature object of Figure class can be used as
reference to objects of Rectangle and Square class. Above program with modification(
shown in bold) in Area_Override class will be as :
class Area_Overrid
{
public static void main(String[] args)
{
Figure f = new Figure(20.9, 67.9);
Rectangle r = new Rectangle( 34.2, 56.3);
Squre s = new Squre( 23.1);
System.out.println("***** Welcome to Override Demo ******");
f.area();
f= r;
System.out.println(" "+f.area());
f = s;
System.out.println(" "+f.area());
}
}
1)
One object can access the private member of the object of the same class.
37
2)
ii
iii
..
3)
..
38
Now can you think what to do if you have to force that derived classes must redefine
the methods of superclass?
Inheritance and
Polymorphism
2.7 POLYMORPHISM
Polymorphism is the capability of a method to do different things based on the object
through which it is invoked or object it is acting upon. For example method
find _area will work definitely for Circle object and Triangle object In Java, the type
of actual object always determines method calls; object reference type doesnt play
any role in it. You have already used two types of polymorphism (overloading and
overriding) in the previous unit and in the current unit of this block. Now we will look
at the third: dynamic method binding. Java uses Dynamic Method Dispatch
mechanism to decide at run time which overridden function will be invoked. Dynamic
Method Dispatch mechanism is important because it is used to implement runtime
polymorphism in Java. Java uses the principle: a super class object can refer to a
subclass object to resolve calls to overridden methods at run time.
If a superclass has method that is overridden by its subclasses, then the different
versions of the overridden methods are invoked or executed with the help of a
superclass reference variable.
Assume that three subclasses (Cricket_Player Hockey_Player and Football_Player)
that derive from Player abstract class are defined with each subclass having its own
Play() method.
abstract class Player // class is abstract
{
private String name;
public Player(String nm)
{
name=nm;
}
public String getName()
// regular method
{
return (name);
39
}
public abstract void Play();
// abstract method: no implementation
}
class Cricket_Player extends Player
{
Cricket_Player( String var)
{
}
public void Play()
{
System.out.println("Play Cricket:"+getName());
}
}
class Hockey_Player extends Player
{
Hockey_Player( String var)
{
}
public void Play()
{
System.out.println("Play Hockey:"+getName());
}
}
class Football_Player extends Player
{
Football_Player( String var)
{
}
public void Play()
{
System.out.println("Play Football:"+getName());
}
}
public class PolyDemo
{
public static void main(String[] args)
{
Player ref;
// set up var for an Playerl
Cricket_Player aCplayer = new Cricket_Player("Sachin"); // makes specific objects
Hockey_Player aHplayer = new Hockey_Player("Dhanaraj");
Football_Player aFplayer = new Football_Player("Bhutia");
// now reference each as an Animal
ref = aCplayer;
ref.Play();
ref = aHplayer;
ref.Play();
ref = aFplayer;
ref.Play();
}
}
Output:
Play Cricket:Sachin
Play Hockey:Dhanaraj
Play Football:Bhutia
Notice that although each method is invoked through ref, which is a reference to
player class (but no player objects exist), the program is able to resolve the correct
40
method related to the subclass object at runtime. This is known as dynamic (or late)
method binding.
Inheritance and
Polymorphism
Making constants
Preventing method to be overridden
Preventing a class to be inherited
The final keyword (as discussed in Unit 3 of Block1 of this course) is a way of
marking a variable as "read-only". Its value is set once and then cannot be changed.
For example, if year is declared as
final int year = 2005;
Variable year will be containing value 2005 and cannot take any other value after
words.
The final keyword can also be applied to methods, with similar semantics: i.e. the
definition will not change. You cannot override a final method in subclasses, this
means the definition is the final one. You should define a method final when you
are concerned that a subclass may accidentally or deliberately redefine the method
(override).
If you want to prevent a class to be inherited, apply the final keyword to an entire
class definition. For example, if you want to prevent class Personal to be inherited
further, define it as follows:
final class Personal
{
// Data members
//Member functions
}
Now if you try to inherit from class Personal
class Sub_Personal extend Personal
It will be illegal. You cannot derive from Personal class since it is a final class.
1)
2)
41
3)
2.9 SUMMARY
In this unit the concept of inheritance is discussed. It is explained how to derive
classes using extends keyword in Java. To control accessibility of data members three
access specifiers: privatepublic, and protected-are discussed. How to write programs
using concept of inheritance, method overriding, need of abstract classes is also
explained. The concept of polymorphism is explained with the help of a programming
example. In the last section of the unit the use of final keyword in controlling
inheritance is discussed.
2.10 SOLUTIONS/ANSWERS
Check Your Progress 1
1)
2)
3)
If some data members of a class are used in internal operations only and there is
no need to provide access of these members to outside world. Such member
data should be declared private. Similarly, those member functions
Which are used for internal communications/operations only should be declared
private.
2)
True
False
False
42
Inheritance and
Polymorphism
Java uses Dynamic Method Dispatch, one of its powerful concepts to implement
method overriding. Dynamic Method Dispatch helps in deciding the version of
the method to be executed. In other words to identify the type of object on
which method is invoked.
2)
// Program to show polymorphism in Java.
abstract class Account
{
public String Name;
public int Ac_No;
Account(String nm,int an )
{
Name=nm;
Ac_No= an;
}
abstract void getAc_Info( );
}
class Saving_Account extends Account
{
private int min_bal;
Saving_Account( String na, int an, int bl)
{
super(na,an);
min_bal= bl;
}
void getAc_Info()
{
System.out.println(Name +"is having Account Number :"+Ac_No);
System.out.println("Minimum Balance in Saving Account :"+Ac_No +"is
Rs:"+min_bal);
}
}
class Current_Account extends Account
{
private int min_bal;
Current_Account( String na, int an, int bl)
43
{
super(na,an);
min_bal= bl;
}
void getAc_Info()
{
System.out.println(Name +"is having Account Number :"+Ac_No);
System.out.println("Minimum Balance in Current Account :"+Ac_No +" is
Rs:"+min_bal);
}
}
public class AccountReference
{
public static void main(String[] args)
{
Account ref;
// set up var for an Animal
Saving_Account s = new Saving_Account("M.P.Mishra", 10001,1000);
Current_Account c = new Current_Account("Naveen ", 10005,15000);
ref =s;
ref.getAc_Info();
ref =c;
ref.getAc_Info();
}
}
Output:
M.P.Mishrais having Account Number: 10001
Minimum Balance in Saving Account: 10001 is Rs: 1000
Naveen is having Account Number: 10005
Minimum Balance in Current Account: 10005 is Rs: 15000
3)
44
Introduction
Objectives
Package
Page Nos.
45
45
46
3.3
3.4
3.5
3.6
3.7
3.8
3.9
3.10
Accessibility of Packages
Using Package Members
Interfaces
Implementing Interfaces
Interface and Abstract Classes
Extends and Implements Together
Summary
Solutions/Answers
49
49
51
53
56
56
57
57
3.0 INTRODUCTION
Till now you have learned how to create classes and use objects in problem solving. If
you have several classes to solve a problem, you have to think about a container
where you can keep these classes and use them. In Java you can do this by defining
packages. Also, Java provides a very rich set of package covering a variety of areas of
applications including basic I/O, Networking, and Databases. You will use some of
these packages in this course. In this unit you will learn to create your own packages,
and use your own created package in programming.
In this unit we will also discuss interface, one of Javas useful features. If we take
Object Orientation into consideration an interface in Java is a subset of the public
methods of a class. The implementation of a class is the code that makes up those
methods. In Java the meaning of interface is different from the meaning in Object
Orientation. An interface is just a specification of a set of abstract methods. If a class
implements the interface, then it is essential for the class to provide an implementation
for all of the abstract methods in the interface. As we have discussed in Unit 2 of this
block that Java does not provide multiple inheritance. You can use interfaces to
overcome the limitation of non-availability of multiple inheritance, because in Java a
class can implement many interfaces. In this unit you will learn to create interfaces
and implement them in classes.
3.1 OBJECTIVES
After going through this unit you will be able to:
45
3.2 PACKAGE
Java programmer creates packages to partition classes. Partitioning of classes helps in
managing the program. The package statement is used to define space to store classes.
In Java you can write your own package. Writing packages is just like you write any
other Java program. You just have to take care of some points during writing
packages, which are given below.
A package is a
collection of
related classes
and interfaces
providing access
protection and
namespace
management.
There must be not more than one public class per file.
All files in the package must be named name_of_class.Java where name_of_class is
the name of the single public class in the file.
The very first statement in each file in the package, before any import statements or
anything put the statement package myPackageName;
Now let us see how to define a package.
3.2.1
Defining Package
CLASSPATH
46
Packages Naming
Space conflicts will arise if two pieces of code declare the same name. The java
runtime system internally keeps track of what belongs to each package. For example,
suppose someone decides to put a Test class in myJava.io, it wont conflict with a
Test class defined in myJava.net package. Since they are in different packages Java
can tell them apart. Just as you tell Mohan Singh apart from Mohan Sharma by their
last names, similarly Java can tell two Test classes apart by seeing their package
names.
But this scheme doesnt work if two different classes share the same package name as
well as class name. It is not unthinkable that two different people might write
packages called myJava.io with a class called Test.You can ensure that package
names do not conflict with each other by prefixing all your packages in the hierarchy.
More about conflict resolution we will discuss in Section 3.4.1 of this Unit.
Java provides various classes and interfaces that are members of various packages that
bundle classes by function: fundamental classes are in Java.lang classes for reading
and writing (input and output) are in Java.io,for applet programming Java.applet and
so on.
47
Now you are aware of the need of putting your classes and interfaces in packages.
Here we again look at a set of classes and try to find why we need to put them in a
package.
Suppose that you write a group of classes that represent a collection of some graphic
objects, such as circles, rectangles, triangles, lines, and points. You also write an
interface, MoveIt is implemented to check if graphics objects can be moved from one
location to another with the help of mouse or not..
We are using interface here which is discussed in Section 3.5 of this unit.
Now let us see the code snippet given below:
//code snippet
public abstract class Graphic
{
...
}
//for Circle, MoveIt is an interface
public class Circle extends Graphic implements MoveIt
{
...
}
//for Triangle, MoveIt is an interface
public class Triangle extends Graphic implements MoveIt
{
...
}
//interface MoveIt
public interface MoveIt
{
// method to check movement of graphic objects.
}
If you closely observe this basic structure of the code snippet given above, you will
find four major reasons to have these classes and the interface in a package. These
reasons are:
i.
ii.
iii.
iv.
Any programmers can easily determine that these classes and interfaces are
related.
Anybody can know where to find classes and interfaces that provide graphicsrelated functions.
The names of your classes wont conflict with class names in other packages,
because the package creates a new namespace.
Your classes within the package can have unrestricted access to one another, yet
still restrict access for classes outside the package.
Now let us create a package named graphics for the above program structure.
This code will appear in the source file Circle.Java and puts the Circle class in the
graphics package.
package graphics;
public class Circle extends Graphic implements MoveIt
{
...
}
48
The Circle class is a public member of the graphics package. Similarly include the
statement in Rectangle.Java, triangle.Java, and so on.
package graphics;
public class Rectangle extends Graphic implements MoveIt
{
...
}
1)
2)
Now we will discuss the accessibility of the classes and interfaces defined inside the
packages.
49
3.
50
package. With the import statement, you can import only a single package member or
an entire package.
For your convenience, the Java runtime system automatically imports two entire
packages: the Java.lang package and the current package by default.
Resolving Name Conflicts
There may be situations in which a member in one package shares the same name
with a member in another package and both packages are imported. In these situations
you must refer to each member by its qualified name. For example, the previous
example defined a class named Rectangle in the graphics package. The Java.awt
package also contains a Rectangle class. If both graphics and Java.awt have been
imported, in this case the following is ambiguous:
Rectangle rect;
In such a situation, you have to be more specific and use the members qualified name
to indicate exactly which Rectangle class you want, for example, if you want
Rectangle of graphics package then write:
graphics. Rectangle rect; //rect is object of graphics. Rectangle class
And if you Rectangle class of Java.awt package then write:
Java.awt. Rectangle rect; //rect is object of Java.awt. Rectangle class
1)
2)
3)
When does name conflict arise in package use? How to resolve it?
Java does not support multiple inheritance. But if you have some implementation
which needs solutions similar to multiple inheritance implementation. This can be
done in Java using interfaces. Now let us see how to define and implement interfaces.
3.5 INTERFACES
Interfaces in Java look similar to classes but they dont have instance variables and
provides methods that too without implementation. It means that every method in the
51
An interface is like
a class with nothing
but abstract methods
and final, static
fields. All methods
and fields of an
interface must be
public.
The interface declaration declares various attributes of the interface such as its name
and whether it extends another interface. The interface body contains the constant and
method declarations within that interface.
Interface Declaration
Interface Body
Method
Declaration
Constant
Declaration
Interface defining is similar to defining a class. You can define an interface as given
below:
52
return_type methoN(patameters);
type variable_Name1;
type variable_Name2;
}
In this declaration access_specifier is either public or not given. If no specifier is
given then interface is available only to the members of the package in which it is
declared. If specifier is given as public, then it is available to all. As you can see,
variables also can be declared within inside of interface but they are final and static by
default. Classes implementing this interface cannot change these variables. All the
methods and variables are by default public, if interface is public otherwise they are
visible to the package in which interface is declared.
Unlike a class, a interface can be added to a class that is already a subclass of another
class. A single interface can apply to members of many different classes. For example
you can define a Calculate interface with the single method calculateInterest().
public interface Calculate
{
public double calculateInterest();
}
Now you can use this interface on many different classes if you need to calculate
interest. It would be inconvenient to make all these objects derive from a single class.
Furthermore, each different type of system is likely to have a different means of
calculating the interest. It is better to define a Calculate interface and declare that each
class implements Calculate.
Many different methods can be declared in a single interface. The method of an
interface may be overloaded. Also in an interface may extend other interfaces just as a
class extend or subclass another class.
53
The interface :
public interface Sleeper
{
public void wakeUpMe();
public long WaitForSec= 1000;
public long WaitForMin=60000;
}
declares two constants that are useful arguments to letMeSleep. All constant values
defined in an interface are implicitly public, static, and final. The use of these
modifiers on a constant declaration in an interface is discouraged as a matter of style.
Any class can use an interfaces constants from the name of the interface, like this:
Sleeper.WaitForSec
Classes that implement an interface can treat the constants as they were inherited.
This is why ControlClock can use WaitForsec directly when calling letMeSleep:
public class ControlClock extends Applet implements Sleeper
{
...
public void wakeUpMe()
{
repaint();
clock.letMeSleepr(this, WaitForSec);
}
}
Note: Member declarations in an interface does not allow for some declaration
modifiers; you may not use transient, volatile, or synchronized in a member
declaration in an interface. Also, you may not use the private and protected specifiers
when declaring members of an interface.
Again let us take example of interface Calculate and implement it in a class:
public interface Calculate
{
public double calculateInterest();
}
In the following program interface Calculate is implemented by SavingAccount class.
54
//program
interface Calculate
{
public double calculateInterest();
}
class SavingAccount implements Calculate
{
int Ac_No;
int Amount;
double Rate_of_Int;
int time;
SavingAccount( int a , double b, int c, int d)
{
Ac_No = a;
Rate_of_Int = b;
time = c;
Amount = d;
}
void DisplayInt()
{
System.out.println("Interest for Account No. "+Ac_No+" is Rs "+calculateInterest());
}
public double calculateInterest( )
{
return( Amount*Rate_of_Int*time/100);
}
}
public class TestIterface
{
public static void main( String args[])
{
SavingAccount S = new SavingAccount( 1010,4.5,5,5000);
S.DisplayInt();
}
}
Output:
Interest for Account No. 1010 is Rs 1125.0
Interface and Inheritance
One interface can inherit another interface using extends keyword. This is
syntactically the same as inheriting classes. Let us say one interface A is inhering
interface B. At the same time a class C is implementing interface A. Then class C will
implement methods of both the interfaces A and B.
See the program given below to show inheritance of interfaces.
//program
interface One
{
void MethodOne( );
}
interface Two extends One
{
public void MethodTwo();
}
class interfaceInherit implements Two
{
public void MethodOne()
{
System.out.println("Method of interface One is implemented");
}
public void MethodTwo()
{
System.out.println("Method of interface Two is implemented");
}
}
class Test
{
public static void main( String args[])
{
System.out.println("Interface Inheritance Demonstration");
interfaceInherit object = new interfaceInherit() ;
object.MethodOne();
object.MethodTwo();
}
}
Output:
55
A class can implement more than one interface, but an abstract class can only
subclass one class.
An abstract class can have non-abstract methods. All methods of an interface
are implicitly (or explicitly) abstract.
An abstract class can declare instance variables; an interface cannot.
An abstract class can have a user-defined constructor; an interface has no
constructors.
Every method of an interface is implicitly (or explicitly) public.
An abstract class can have non-public methods.
1)
What is an interface?
2)
56
3)
Show through a program that fields in an interface are implicitly static and final
and methods are automatically public.
3.9 SUMMARY
In this unit the concepts of packages and interfaces are discussed. This unit explains
the need of packages, how to create package, and the need of setting CLASSPATH
variable is discussed. It is also discussed how members of packages are imported in a
program and how to remove name conflicts if any. In this unit we have also discussed
the need of Interfaces, how interfaces are declared, how an interface is implemented
by a class. In the last two sections of this unit we have discussed differences between
abstract classes and interfaces and explained how a class may inherit from a class and
implement interfaces.
3.10 SOLUTIONS/ANSWERS
Check your Progress 1
1)
3)
//program
package AccountPaack;
class Account
{
String Name;
int AccountNo;
String Address;
Account( String n, int a, String c)
{
57
Name = n;
AccountNo = a;
Address = c;
}
void Accout_Information()
{
System.out.println("Name of the Account holder :"+ Name);
System.out.println("Account Number:"+AccountNo);
System.out.println("Address of Account holder :"+Address);
}
}
class AccoutTest
{
public static void main( String args[])
{
Account AcH1 = new Account("Rajeev",110200123, "28-K Saket, New Delhi");
Account AcH2 = new Account("Naveen",110200113, "D251,Sector-55, Noida");
AcH1.Accout_Information();
AcH2.Accout_Information();
}
}
Output:
Name of the Account holder :Rajeev
Account Number:110200123
Address of Account holder :28-K Saket, New Delhi
Name of the Account holder :Naveen
Account Number:110200113
Address of Account holder :D251,Sector-55, Noida
2)
Naming conflict arise when one package share the same name with a member
another package and both packages are imported.
Naming conflict can be resolved using qualified name of the members to be imported.
2)
58
{
void MethodOne( );
int MyValue1 = 100;
}
interface Second
{
public void MethodTwo();
int MyValue2 = 200;
}
class interfaceIn implements First,Second
{
public void MethodOne()
{
System.out.println("Method of interface First is implemented with
value:"+MyValue1);
}
public void MethodTwo()
{
System.out.println("Method of interface Second is implemented with
value:"+MyValue2);
}
}
class TwoInterfTest
{
public static void main( String args[])
{
interfaceIn object = new interfaceIn() ;
object.MethodOne();
object.MethodTwo();
}
}
Output:
Method of interface First is implemented with value:100
Method of interface Second is implemented with value:200
3)
//program
interface MyInterface
{
void MyMethod( );
int MyValue1 = 500;
}
class MyinterfaceImp implements MyInterface
{
public void MyMethod()
{
System.out.println("Method of interface MyInterface is implemented with
value:"+MyValue1);
//MyValue1 += 50;
}
}
class InterfaceTest
{
public static void main( String args[])
{
MyinterfaceImp object = new MyinterfaceImp() ;
object.MyMethod();//myMethod is by default public.
}
}
59
Output:
Method of interface MyInterface is implemented with value:500
If you remove comment (//) from statement //MyValue1 += 50; and compile this
program you will get :
---------- Compile ---------InterfaceTest.java:12: cannot assign a value to final variable MyValue1
MyValue1 += 50;
^
1 error
This error is because of attempt to modify final variable MyValue1.
60
Exceptions Handling
Introduction
Objectives
Exception
Handling of Exception
Page Nos.
61
61
61
62
4.4
4.5
4.6
4.7
4.8
Types of Exceptions
Throwing Exceptions
Writing Exception Subclasses
Summary
Solutions/Answers
69
71
75
75
4.0 INTRODUCTION
During programming in languages like c, c++ you might have observed that even
after successful compilation some errors are detected at runtime. For handling these
kinds of errors there is no support from programming languages like c, c++. Some
error handling mechanisms like returning special values and setting flags are used to
determine that there is some problem at runtime.
In C++ programming language there is a very basic provision for exception handling.
Basically exception handlings provide a safe escape route from problem or clean-up
of error handling code.
In Java exception handling is the only semantic way to report error .In Java exception
is an object, which describes error condition, occurs in a section of code. In this unit
we will discuss how exceptions are handled in Java, you will also learn to create your
own exception classes in this unit.
4.1 OBJECTIVES
After going through this unit you will be able to:
describe exception;
explain causes of exceptions;
writing programs with exceptions handling;
use builtin exceptions;
create your own exception classes.
4.2 EXCEPTION
An exceptional condition is considered as a problem, which stops program execution
from continuation from the point of occurrence of it. Exception stops you from
continuing because of lack of information to deal with the exception condition. In
other words it is not known what to do in specific conditions.
If the system does not provide it you would have to write your own routine to test for
possible errors. You need to write a special code to catch exceptions before they
cause an error.
61
If you attempt in a Java program to carry out an illegal operation, it does not
necessarily halt processing at that point. In most cases, the JVM sees for the
possibility of catching the problem and recovering from it.
If the problems are such which can be caught and recovery can be provided, then we
say the problems are not fatal, and for this the term exception is used rather than
error.
Now let us see what to do if exceptions occur.
Causes of Exception
Exception arises at runtime due to some abnormal condition in program for example
when a method. For division encounters an abnormal condition that it can't handle
itself, i.e. divide by zero, then this method may throw an exception.
Exception
is an
abnormal
condition
If a program written in Java does not follow the rule of Java language or violates the
Java execution environment, constraints exception may occur. There may be a
manually generated exception to pass on some error reports to some calling certain
methods.
If an exception is caught, there are several things that can be done:
i.
ii.
iii.
iv.
v.
vi.
62
Exceptions Handling
{
public static void main(String[] args)
{
int data[] = {2,3,4,5};
System.out.println("Value at : " + data[4]);
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException
at Excep_Test.main(Excep_Test.java:6)
Exception in thread "main"
At runtime this program has got ArrayIndexOutOfBoundsException.This exception
occurs because of the attempt to print beyond the size of array.
Now let us see how we can catch this exception.
To catch an exception in Java, you write a try block with one or more catch clauses.
Each catch clause specifies one exception type that it is prepared to handle. The try
block places a fence around the code that is under the watchful eye of the associated
catchers. If the bit of code delimited by the try block throws an exception, the
associated catch clauses will be examined by the Java virtual machine. If the virtual
machine finds a catch clause that is prepared to handle the thrown exception, the
program continues execution starting with the first statement of that catch clause, and
the catch block is used for executing code to handle exception and graceful
termination of the program.
public class Excep_Test
{
public static void main(String[] args)
{
try
{
int data[] = {2,3,4,5};
System.out.println("Value at : " + data[4]);
}
catch( ArrayIndexOutOfBoundsException e)
{
System.out.println("Sorry you are trying to print beyond the size of data[]");
}
}
}
Output:
Sorry you are trying to print beyond the size of data[]
In this program you can observe that after the occurrence of the exception the
program is not terminated. Control is transferred to the catch block followed by try
block.
4.3.2
Sometimes there may be a chance to have multiple exceptions in a program. You can
use multiple catch clauses to catch the different kinds of exceptions that code can
throw. If more than one exception is raised by a block of code, then to handle these
exceptions more than one catch clauses are used. When an exception is thrown,
different catch blocks associated with try block inspect in order and the first one
whose type (the exception type passed as argument in catch clause) matches with the
exception type is executed This code snippet will give you an idea how to catch
multiple exceptions.
//code snippet
63
try
{
// some code
}
catch (NumberFormatException e)
{
//Code to handle NumberFormatException
}
catch (IOException e)
{
// Code to handle IOException
}
catch (Exception e)
{
// Code to handle exceptions than NumberFormatException and IOException
}
finally // optional
{
//Code in this block always executed even if no exceptions
}
Now let us see the program given below :
//program
public class MultiCatch
{
public static void main(String[] args)
{
int repeat ;
try
{
repeat = Integer.parseInt(args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
// pick a default value for repeat
repeat = 1;
}
catch (NumberFormatException e)
{
// print an error message
System.err.println("Usage: repeat as count" );
System.err.println("where repeat is the number of times to say Hello Java" );
System.err.println("and given as an integer like 2 or 5" );
return;
}
for (int i = 0; i < repeat; i++)
{
System.out.println("Hello");
}
}
}
Output:
Hello
Output of the above program is Hello. This output is because of no argument is
passed to program and exception ArrayIndexOutOfBoundsException occurred. If
pass some non-numeric value is as argument to this program you will get some other
output. Check what output you are getting after passing Java as argument.
64
Exceptions Handling
It is important to ensure that something happens upon exiting a block, no matter how
the block is exited. It is the programmers responsibility to ensure what should
happen. For this finally clause is used.
1)
.
.
.
2)
.
.
3)
.
4.3.3
There are several ways of exiting from a block of code (the statements between two
matching curly braces). Once a JVM has begun to execute a block, it can exit that
block in any of several ways.
It could, for example simply exit after reaching the closing curly brace.
It could encounter a break, continue, or return statement that causes it to jump out of
the block from somewhere in the middle.
If an exception is thrown that isnt caught inside the block, it could exit the block
while searching for a catch clause.
Let us take an example, of opening a file in a method. You open the file perform
needed operation on the file and most importantly you want to ensure that the file
65
gets closed no matter how the method completes. In Java, this kind of desires are
fulfilled with the help of finally clause.
A finally clause is included in a program in the last after all the possible code to be
executed. Basically finally block should be the last block of execution in the program.
//program
public class Finally_Test
{
public static void main(String[] args)
{
try
{
System.out.println("Hello " + args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Hello, You are here after ArrayIndexOutOfBoundsException");
}
finally
{
System.out.println("Finally you have to reach here");
}
}
}
Output:
Hello, You are here after ArrayIndexOutOfBoundsException
Finally you have to reach here
Note: At least one clause, either catch or finally, must be associated with each try
block. In case you have both catch clauses and a finally clause with the same try
block, you must put the finally clause after all the catch clauses.
Now let us discuss the types of exceptions that occur in Java.
Unchecked exceptions
Basically, an unchecked exception is a type of exception for that you option that
handle it, or ignore it. If you elect to ignore the possibility of an unchecked
exception, then, as a result of that your program will terminate. If you elect to handle
an unchecked exception that occur then the result will depend on the code that you
have written to handle the exception. Exceptions instantiated from
RuntimeException and its subclasses are considered as unchecked exceptions.
Checked exceptions
66
Exceptions Handling
Checked exceptions are those that cannot be ignored when you write the code in your
methods. According to Flanagan, the exception classes in this category represent
routine abnormal conditions that should be anticipated and caught to prevent program
termination.
All exceptions instantiated from the Exception class, or from subclasses, of
Exception other than RuntimeException and its subclasses, must either be:
(i)
(ii)
67
+ class java.lang.IllegalArgumentException
|
+ class java.lang.Error
Figure 1: Throwable Class Partial Hierarchy
4.4.2
Runtime Exceptions
Programming errors that should be detected in testing for example index out of
bounds, null pointer, illegal argument, etc. are known as runtime exception. Runtime
exceptions do need to be handled (They are of the types that can be handled), but
errors often cannot be handled.
Most of the runtime exceptions (members of the RuntimeException family) are
thrown by the Java virtual machine itself. These exceptions are usually an indication
of software bugs. You know problems with arrays, such as
ArrayIndexOutOfBoundsException, or passed parameters, such as
IllegalArgumentException, also could happen just about anywhere in a program.
When exceptions like these are thrown, you have to fix the bugs that caused them to
be thrown.
Sometimes you have to decide whether to throw a checked exception or an
unchecked runtime exception. In this case you must look at the abnormal condition
you are signalling. If you are throwing an exception to indicate an improper use of
your class, then here you are signalling a software bug. In this case the class of
exception you throw probably should descend from RuntimeException, which will
make it unchecked. Otherwise, if you are throwing an exception to indicate not a
software bug but an abnormal condition, then you have to deal with it every time
your method is used. In other words your exception should be checked.
The runtime exceptions are not necessarily to be caught. You dont have to put a trycatch for runtime exceptions, for example, every integer division operation to catch a
divide by zero or around every array variable to watch for whether it is going out of
bounds. But it is better if you handle possible runtime exceptions. If you think there is
a reasonable chance of such exceptions occurring.
68
Exceptions Handling
1)
Explain the exception types that can be caught by the following code.
try
{
//operations
}
catch (Exception e)
{
//exception handling.
}
2)
3)
Is there anything wrong with this exception handing code? Will this code
compile?
try
{
//operation code...
}
catch (Exception e)
{
//exception handling
}
catch (ArithmeticException ae)
{
// ArithmeticException handling
}
4)
69
//code snippet
public static void copy (InputStream in, OutputStream out)
throws IOException
{
byte[] Mybuf = new byte[256];
while (true)
{
int bytesRead = in.read(Mybuf);
if (bytesRead == -1) break;
out.write(Mybuf, 0, bytesRead);
}
}
In this code snippet copy method throws IOException, and now the method invoke
copy method is responsible for handling IOException.
Sometime single method may have to throw more than one type of exception. In this
case the exception classes are just separated by commas. For example in the code:
public MyDecimal
public divide(MyDecimal value, int roundMode) throws ArithmeticException,
IllegalArgumentException
The divide method throws two exceptions ArithmeticException, and
IllegalArgumentException.
See the program given below written for showing how IllegalArgumentException
exceptions are thrown if arguments are not passed properly.
//program
class MyClock
{
int hours ,minutes, seconds;
public MyClock(int hours, int minutes, int seconds)
{
if (hours < 1 || hours > 12)
{
throw new IllegalArgumentException("Hours must be between 1 and 12");
}
if (minutes < 0 || minutes > 59)
{
throw new IllegalArgumentException("Minutes must be between 0 and 59");
}
if (seconds < 0 || seconds > 59)
{
throw new IllegalArgumentException("Seconds must be between 0 and 59");
}
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
public MyClock(int hours, int minutes)
{
this(hours, minutes, 0);
}
public MyClock(int hours)
{
this(hours, 0, 0);
}
70
Exceptions Handling
}
public class ThrowTest
{
public static void main( String args [])
{
try
{
MyClock clock = new MyClock(12, 67,80);
}
catch( IllegalArgumentException e)
{
System.out.println("IllegalArgumentException is caught....");
}
}
}
Output:
IllegalArgumentException is caught....
Now let us see how own exception subclasses can be written.
71
if(a>10)
throw new MyException(a);
System.out.println("Normal Exit of compute method[for Value="+a +"]");
}
public static void main(String args[])
{
try
{
compute(5);
compute(25);
}
catch(MyException e)
{
System.out.println("MyException Caught :"+e);
}
}
}
Output:
Call compute method (5)
Normal Exit of compute method [for Value=5]
Call compute method (25)
MyException Caught: MYException [for Value=25]
Embedding information in an exception object
You can say that when an exception is thrown by you ,it is like performing a kind of
structured go-to from the place in your program where an abnormal condition was
detected to a place where it can be handled. The Java virtual machine uses the class
of the exception object you throw to decide which catch clause, if any, should be
allowed to handle the exception.
But you cannot take an exception just as a transfer control from one part of your
program to another, it also transmits information. As mentioned earlier the exception
is a full-fledged object that you can define yourself. Also you can embed information
about the abnormal condition in the object before you throw it. The catch clause can
then get the information by querying the exception object directly.
The Exception class allows you to specify a String detail message that can be
retrieved by invoking getMessage() of Throwable class on the exception object. In
your program at the time of defining it you can give the option of specifying a detail
message like this:
class NotAcceptableValuException extends Exception
{
NotAcceptableValuException
{
}
NotAcceptableValuException (String msg)
{
super(msg);
}
}
Given the above declaration of NotAcceptableValuException, now you can create an
object of NotAcceptableValuException in one of two ways:
new NotAcceptableValuException ()
new NotAcceptableValuException ("This Value is not Acceptable.")
Now a catch clause can query the object for a detail string, like this code snippet:
class MyValue
72
Exceptions Handling
{
public void serveCustomers()
{
try
{
// operations
}
catch (NotAcceptableValuException e)
{
System.out.println (NotAcceptableValuException Caught:+e);
}
}
}
If during operations NotAcceptableValuException is generated and throw it will be
handled by catch then statement
System.out.println (NotAcceptableValuException Caught:+e);
will print:
NotAcceptableValuException Caught:" This Value is not Acceptable." provided
NotAcceptableValuException object is created as:
new NotAcceptableValuException ("This Value is not Acceptable.") ;
1)
.
2)
Write a program to create your own exception subclass that throws exception if
the sum of two integers is greater that 99.
3)
73
74
Exceptions Handling
4.7 SUMMARY
This unit discusses how Java goes to great lengths to help you deal with error
conditions. In this unit we have discussed how Java's exception mechanisms give a
structured way to perform a go-to from the place where an error occurs to the code
that knows how to handle the error. In this unit we have discussed different causes of
exception, using try, catch, finally, throw and throws clauses in exception handling.
This unit deals with ways to handle error conditions in a structured, methodical way.
This unit discusses types of exceptions, Throwable class hierarchy, and explains how
to write own exception subclasses.
4.8 SOLUTIONS/ANSWERS
Check Your Progress 1
1)
2)
Yes, it is legal. It is not necessary for a try statement to have a catch statement
if it has a finally statement. If the code in the try statement has multiple exit
points and no catch clauses are associated to the code, then code in the finally
statement is executed no matter how the try block is exited.
3)
//program
public class TwoCatch_Test
{
public static void main(String[] args)
{
try
{
int i = 1;
int data[] = {2,3,4,5};
System.out.println("Value at : " + data[2]);
i = i/(i-i);
}
catch( ArrayIndexOutOfBoundsException e)
{
System.out.println("Sorry you are trying to print beyond the size of data[]");
}
catch(ArithmeticException e)
{
System.out.println("Divide By 0 :"+e);
75
}
}
}
Output:
Value at: 4
Divide By 0: java.lang.ArithmeticException: / by zero
This code will handle catch exceptions of type Exception; therefore, it will
catch any exception. This can be a poor implementation because you are losing
valuable information about the type of exception being thrown and making
your code less efficient. It is better to handle different exceptions on the basis
of their actual type, which may be ArithmeticException, or
IllegalArgumentException or anything else
2)
3)
4)
76
1)
A method in Java can throw exception using throws keyword. In code snippet
below MyMethod() throws an ArrayOutOfBoundsExceptio:
//code snippet
class TestTrows
{
void MyMethod() throws ArrayOutOfBoundsException
{
// operation code
throw ArrayOutOfBoundsException(My ArrayOutOfBoundsException);
}
2)
//program
Exceptions Handling
Output:
***** Welcome to Stack operations ****
StackException: overflow
Top of MyStack : Learn it
Popping data...
Learn it
Good for all
1.4
Java
Hi
77