You are on page 1of 41

CS 547

ADVANCED PROGRAMMING
(Lecture Note 3: Packages, Abstract Class, Interface, Inner class & Exception
Handling)
By
Isma’il Aliyu
Department of Mathematical Sciences
ATBU, Bauchi.
2020/2021 Session
Package
• Java allows you to group classes in a collection called a
package.
– A package in Java is name giving to a folder or directory for
keeping source files.
• Packages are convenient for organizing your work and for
separating your work from code libraries provided by
others. The main reason for using packages is to guarantee
the uniqueness of class names.
• The standard Java library is distributed over a number of
packages; such as java.lang, java.util, java.net, and so on.
• The standard Java packages are examples of hierarchical
packages. Just as you have nested subdirectories on your
hard disk

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 2


Class Importation
• A class can use all classes from its own package. It can
equally use all public classes from other packages.
• There re two ways to access public classes in another
package.
i. Add the full package name in front of every class name. eg
• java.util.Date today = new java.util.Date();
• java.util.Scanner in = new java.util.Scanner(System.in);
ii. Use the import statement
• The import statement is placed at the top of the source file
before class declaration.
• You can import a specific class or the all the classes in the
package.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 3


Import Statement
• The Date class of the java.util package can be imported as
follows;
– import java.util.Date;
• Then you can use this statement without package prefix
– Date date = new Date();
• To import all the classes in a package, we use the * while
card. So the following import statement import all the
classes in the util package.
– import java.util.*;
• The java.util.* syntax is less tedious. It has no negative
effect on code size. However, if you import classes
explicitly, the reader of your code knows exactly which
classes you use.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 4


Advanced Topics in OOP
• So far, you have seen the basics for object-oriented
programming in Java.
• The subsequent slides presents several advanced
object oriented programming topics/techniques.
• Despite their less obvious nature, you will need to
master them.
• These advanced topics include:
– Abstract classes
– Interfaces
– Inner classes
– Exception handling

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 5


Abstract Classes
• In an inheritance set up, good class design should
ensure that a superclass contains common features of
its subclasses.
• Sometimes, as you move up the inheritance hierarchy,
classes become more general and probably more
abstract.
• At some point, the ancestor class becomes so general
that you think of it more as a basis for other classes
than as a class with specific instances you want to use.
• That is, sometimes a superclass is so abstract that it
cannot have any specific instances. Such a class is
referred to as an abstract class.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 6


Abstract Class
• Sometimes, subclasses have common features (usually methods)
but they differ in the way they implement such methods.
• In that case the method should be declared as abstract method in
the superclass.
– Suppose we are writing program involving geometric objects . So we
have Shape as superclass while Circle, Triangle, and Rectangle as
subclasses. Since you can compute areas and perimeters for all
geometric objects, it is better to define the getArea() and
getPerimeter() methods in the Shapes class. However, these methods
cannot be implemented in the Shapes class, because their
implementation depends on the specific type of geometric object.
Such methods should be declared as abstract methods. Abstract
methods are denoted using the abstract modifier in the method
declaration.
– When a class has one or more abstract method, then it must be
declared as abstract class.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 7


Abstract Class
• Abstract classes are like regular (concrete) classes, but they
cannot be instantiated using the new operator.
• The constructor in the abstract class is defined protected,
because it is used only by subclasses. When you create an
instance of a subclass, its superclass’s constructor is
invoked to initialize data fields defined in the superclass.
• Therefore, abstract class is a class that contain one or more
abstract method and cannot be instantiated by other
classes outside the inheritance hierarchy.
• Abstract class is usually a superclass in an inheritance
setup, and only its subclass can use its functionalities.
• An abstract method is defined without implementation. Its
implementation is provided by the subclasses

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 8


Abstract Class declaration
• Abstract classes are declared by adding the keyword
abstract before the class name
• Consider the following example;
public abstract class Animal {
// other members here
public abstract void move () ;
}
• In the above code snippet, a class Animal is declared as
abstract and has one abstract method declaration as well.
• Any class that extends Animal must provide its own
implementation of the movement method.
• Eg; the implementation of move method for Fish could vary
from that of Bird or Goat. Remember, they are all animals.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 9


Abstract Class – Example
• In an object-oriented drawing application, you can draw
circles, rectangles, lines, triangle and many other graphic
objects.
• These objects all have certain states (for example: position,
orientation, line color, fill color) and behaviors (for
example: moveTo, rotate, resize, draw) in common.
• Some of these states and behaviors are the same for all
graphic objects (for example: position, fill color, and
moveTo). Others require different implementations (for
example, resize or draw).
• All GraphicObjects must be drawn or resized; they just
differ in how to do it.
• This is a perfect situation for an abstract superclass.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 10


Abstract Class – Example
• First, we declare an abstract
class, GraphicObject, to
provide member variables and
methods that are wholly
public abstract class GraphicObject {
shared by all subclasses, such int x, y;
as the current position and the ...
moveTo method. public void moveTo(int newX, int newY)
{
• GraphicObject also declares ...
abstract methods for methods, }
public abstract void draw();
such as draw or resize, that public abstract void resize();
need to be implemented by all }
subclasses but must be
implemented in different
ways.
• The GraphicObject class can
look something like this:

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 11


Abstract Class – Example
• Each nonabstract subclass
of GraphicObject, such as public class Rectangle extends GraphicObject {
Circle and Rectangle, must void draw() {
provide implementations ...
for the draw and resize }
methods: void resize() {
...
public class Circle extends GraphicObject }
{ }
void draw() {
...
}
void resize() {
...
}
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 12


Abstract Class
• Note that an Abstract class can implements an
interface.
• In that case, it must implement all of the
interface's methods.
• Example;
public abstract class X implements Y {
// implements all but one method of Y
}
• What is an interface?
– Next slide pls.
CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 13
Interface
• In its most common form, an interface is a group of related
methods with empty bodies.
• A class that implements a particular interface must
provides implementation of method(s) in the interface.
– “If your class conforms to a particular interface, then I’ll perform
the service”.
• A class can implement one or more interfaces.
• Implementing an interface is like signing a contract with the
compiler that states,
– “I will declare all the methods specified by the interface ”
• All methods of an interface are automatically public.
– For that reason, it is not necessary to supply the keyword public
when declaring a method in an interface.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 14


Interface vs Abstract class
• Abstract classes are similar to interfaces.
– They cant be instantiated (you cant create their objects) , and
– They may contain a mix of methods declared with or without an
implementation.
• However, there are some differences between the two:
– Interfaces never have instance fields.
– Methods of the interface can never be abstract methods.
– While abstract classes are subclassed, an interface can not subclassed
– Unlike abstract class which is usually a super class in an inheritance set
up, any classes can only implements Interface but can not extends it.
– Methods are never implemented in the interface but some methods
(non-abstract) are implemented in an abstract class.
• Supplying instance fields and method implementations is the job of the classes
that implement the interface.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 15


Interface – declaration
• The syntax of interface declaration is similar to that of class but the
keyword class is replaced with interface.
public interface InterfaceName {
// methods ;
}
• Example,
public interface SimpleInterface {
void performAction();
}
• In the code snippet above, the interface which we named
SimpleInterface declares just one method with name
performAction.
– This means any class that implements the SimpleInterface is required
to have a performAction method, and the method doesn’t accept any
parameter.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 16


Interface – Example
• Implementing an interface allows •
a class to become more formal public interface Bicycle {
about the behavior it promises to // wheel revolutions per minute
provide. Interfaces form a void changeCadence(int newValue);
contract between the class and void changeGear(int newValue);
the outside world, and this void speedUp(int increment);
void applyBrakes(int decrement);
contract is enforced at build time
}
by the compiler.
• If your class claims to implement
an interface, all methods defined • To implement this interface, the
by that interface must appear in name of your class would change
its source code before the class (to a particular brand of bicycle,
will successfully compile for example, such as
ACMEBicycle), and you'd use the
implements keyword in the class
• A bicycle's behavior, if specified declaration:
as an interface, might appear as
follows:

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 17


Interface – Example
public class ACMEBicycle implements void changeGear(int newValue) {
Bicycle { gear = newValue;
int cadence = 0; }
int speed = 0; void speedUp(int increment) {
int gear = 1; speed = speed + increment;
/* The compiler will now require that }
methods changeCadence, changeGear,
speedUp, and applyBrakes all be void applyBrakes(int decrement) {
implemented. Compilation will fail if speed = speed - decrement;
thosenmethods are missing from this
class. */ }
void changeCadence(int void printStates(){
newValue) { System.out.println("cadence:“+cad
cadence = newValue; ence + " speed:" +nspeed + " gear:"
+ gear);
} }
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 18


Inner Class?
• Next, we move on to the mechanism of inner classes.
• Java programming language allows you to define a class within
another class. Such a class is called a nested class or inner class.
– An Inner class is a class that is defined inside another class.
• Inner classes are useful when you design collections of cooperating
classes.
• In particular, inner classes enable you to write concise, professional
looking code to handle GUI events.

class OuterClass {
... class InnerClass {

... }
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 19


Inner classes?
• A nested class (inner) is a member of its enclosing
class.
– an inner class can access the fields and methods of the
surrounding or outer class – including data that would
otherwise be private.
• An inner class is associated with an instance of its
enclosing class and has direct access to that object's
methods and fields. Also, because an inner class is
associated with an instance, it cannot define any static
members itself.
• An instance of InnerClass can exist only within an
instance of OuterClass and has direct access to the
methods and fields of its enclosing instance.
CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 20
Inner class?
• To instantiate an inner class, you must first instantiate
the outer class.
• Then, create the inner object within the outer object
with this syntax:
– OuterClass outerObject = new OuterClass();
– OuterClass.InnerClass innerObject = outerObject.new
InnerClass();
• There are two special kinds of inner classes:
– local classes and
– anonymous classes.
• Anonymous inner classes are handy when you want to
define callbacks without writing a lot of code.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 21


Why use Inner class?
• Compelling reasons for using nested classes include the following:
• It is a way of logically grouping classes that are only used in one
place:
– If a class is useful to only one other class, then it is logical to embed it
in that class and keep the two together. Nesting such "helper classes"
makes their package more streamlined.
• It increases encapsulation:
– Consider two top-level classes, A and B, where B needs access to
members of A that would otherwise be declared private. By hiding
class B within class A, A's members can be declared private and B can
access them. In addition, B itself can be hidden from the outside
world.
• It can lead to more readable and maintainable code:
– Nesting small classes within top-level classes places the code closer to
where it is used.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 22


Exception Handling
• Exception?
– An exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions
• When an Exception occurs, the normal flow of the program
is disrupted and the program terminates abnormally.
• Exception handling?
– is the mechanism of dealing with exceptions in order to
maintain normal flow of control.
• An exception can occur for many different reasons, eg:
– A file to be read or written to cannot be found.
– Establishing connection to database that does not exist.
– A user has entered invalid data.
– A class not found

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 23


Exception Handling
• Some of these exceptions are caused by users, others
by programmer, and others by physical resources that
have failed in some manner during program execution.
• When exception occur, if not appropriately handled the
program abruptly crash or terminate.
• This is bad. A program should be able to handle error
situations gracefully when they occur at runtime.
• Java and other Object Oriented languages provide
exception handling for this purpose.
• There are two categories of exceptions:
– Checked
– Unchecked

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 24


Exception Hierarchy
• The Exception class is a • .
subclass of Throwable class
• Some of the methods in the
Throwable class are:
– getMessage – Returns a
detailed message about the
exception that has occurred.
This message is initialized in
the Throwable constructor.
– getCause – Returns the cause
of the exception as represented
by a Throwable object.
– printStackTrace – Prints the
result of toString along with
the stack trace to System.err,
the error output stream.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 25


Checked Exceptions
• Checked exceptions occur at the compile time.
They are also called compile time exceptions.
• These exceptions cannot simply be ignored at the
time of compilation. Programmer should take
care of them.
• For example: If FileReader class is used in your
program to read data from a file, if the file
specified in its constructor doesn't exist, then a
FileNotFoundException occurs.
• Examples of checked exceptions are given in the
table below
CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 26
Checked Exceptions
Exception Description
Exception Represent all types of exceptions
ClassNotFoundException Class not found
InterruptedException One thread has been interrupted by another
NoSuchMethodException Method not found
IOException Exception related to Input Output operations
 EOFException
 FileNotFoundException

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 27


Unchecked Exceptions
• Unchecked Exceptions are also called runtime
exceptions because they occur at run time
(during execution).
• These include programming bugs such as;
logic errors, improper use of an API, division
by 0, wrong casting, accessing index of array
that does not exist etc.
• The following table list some examples of Run
time exceptions.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 28


Unchecked Exceptions

ArithmeticException Arithmetic errors such as division by 0


ClassCastException Invalid cast
NumberFormatException Invalid conversion of string to numeric form
IndexOutOfBoundsException Array index is out-of-bound
 ArrayIndexOutOfBoundsException  Attempt to index outside the bounds of
 StringIndexOutOfBoundsException array
 Attempt to index outside the bounds of a
string
NullPointerException Invalid use of null reference
IllegalArgumentException Illegal argument used to invoke method
UnsuportedOperationException Unsupported operation is encountered

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 29


Exception Handling in Java
• When an exception occurs, the method
currently executing creates an exception
object and passes it to the runtime system,
which looks for a special block of code, called
an exception handler, that deals with the
exception.
• The following keywords are used for exception
handling in java:
– try, catch, finally, throws, throw.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 30


try and catch
• try and catch are always use together.
• The try block houses the code that may trigger
the exception while the catch block handles it.
• Thus the catch block usually contain the actions
(statements) to be executed when the exception
occurs.
• A catch statement involves declaring the type of
exception you are trying to catch.
• Every try block must have at least one or more
catch blocks and followed by a finally block.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 31


try & catch

try{ try{
// exception prone code // exception prone code
}catch(ExceptionName e){ }catch(ExceptionName1 e1){
// catch block // catch block1
} } catch(ExceptionName2 e2){
// catch block2
• A try block can be followed } catch(ExceptionNameN eN){
by multiple catch blocks // catch blockN
• See the next example. }

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 32


finally
• The finally block follows try and catch blocks.
• A finally block appears at the end of the catch
block
• The code in the finally block always executes
irrespective of occurrence of an Exception.
• You can use a finally block to run any clean up
statements (eg, closing a handle).
• Example:
– The tryAndCatchDemo method below demonstrates
how to catch multiple exceptions.
– The method also shows how to use finally keyword.
CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 33
finally

– The method allow user to enter an integer value. It then divides


100 by the number entered.
– The method also read a text file in a given directory/location
and then writes the text “Exception Demonstration”‖ to the text
file.
– Two exceptions are likely to occur in this method, one is
checked exception and the other is unchecked exception.
– The two exceptions were all caught/handled.
– The first exception occurs when the file does not exist in the
specified path or writing to the file could not be completed due
to other reasons.
– The second exception occurs when the number entered is 0.
This will trigger exception because of division by 0.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 34


Example – exception handling
out.println(content);
public void tryAndCatchDemo(){ }catch(IOException ioe){
Scanner in = new Scanner(System.in); System.out.println("Writing to file not
int val = in.nextInt(); successful: "+ ioe.getMessage());
String content = "Exception }catch(ArithmeticException ae){
Demonstration"; System.out.println("Invalid input.
String filePath = "C:/JP/myfile.txt"; Please enter a number > 0.");
PrintWriter out = null; }finally{
try{ in.close();
double r = 100/(double)val; out.close();
System.out.println("100 divide by }
number you entered is: "+ r); }
File f = new File(filePath);
FileWriter fw = new FileWriter(f);
out = new PrintWriter(fw);

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 35


throws
• The throws keyword is used as part of method
signature.
– It appears at the end of a method's signature.
• The throws keyword is used to declare or indicate that
a specified exception may occur in the course of
executing the statements in that method.
• Thus it provide information to programmer that there
may be exception when that method is called and
therefore appropriate exception handling mechanisms
must be used.
• See example in the next slide
CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 36
throws - example

public Image LoadImage (String path) throws IOException {


// statements
}
• If a method might throw more than one checked exception
type, you must list all exception classes in the header.
Separate them by a comma as in the following example

public Image LoadImage (String path) throws EOFException,


MalFormedURLExcetion {
// statements
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 37


throw
• The throw keyword is used to – Note difference in the way in
explicit invoke or throw an which the exception were
exception. thrown.
– In both case, the exception
• It can be used to throw either were not caught inside the
checked or unchecked methods.
exception. – Therefore, the task of catching
• The throw keyword is mostly or handling the thrown
used to throw custom exception is left to a method
exception. that invokes them
• Consider examples below:
– The loadFile method throws
IOException.
– Similarly, getElement method
throw
IndexOutOfBoundException.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 38


throws & throw – example

public File loadFile(String path) throws IOException{


File f = new File(path);
return f;
}

public int getElement(int[] theArray, int index){
if(index < 0 && index >= theArray.length)
throw new IndexOutOfBoundsException();
else
return theArray[index];
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 39


User-defined Exception
• Java enable programmers to • These are considered to be
create their own exceptions checked exceptions.
so that they can throw and • We can define our own
catch them when the need Exception class as below:
arises. class OurException extends
• User-defined exceptions are Exception {
created as subclasses of
Exception. //……
– That is you just need to }
extend the predefined • If you want to write a
Exception class to create your
own Exception. runtime (unchecked)
exception, you need to
extend the
RuntimeException class

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 40


Summary Exception Handling
• In summary, a method must declare all the checked
exceptions that it might throw.
• Unchecked exceptions are either beyond your control
(Error) or result from conditions that you should not have
allowed in the first place (RuntimeException).
• If your method fails to faithfully declare all checked
exceptions, the compiler will issue an error message.
• Of course, as you have already seen in quite a few
examples, instead of declaring the exception, you can also
catch it. Then the exception won‘t be thrown out of the
method, and no throws specification is necessary.
• You later saw how to decide whether to catch an exception
or to enable someone else to catch it.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 41

You might also like