0% found this document useful (0 votes)
16 views22 pages

Unit 4

Unit 4 covers interfaces and packages in Java, focusing on abstract classes, methods, and the purpose of interfaces. It explains how to create and declare interfaces, implement multiple interfaces, and the differences between abstract classes and interfaces. The unit also includes examples and guidelines for when to use abstract classes versus interfaces.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views22 pages

Unit 4

Unit 4 covers interfaces and packages in Java, focusing on abstract classes, methods, and the purpose of interfaces. It explains how to create and declare interfaces, implement multiple interfaces, and the differences between abstract classes and interfaces. The unit also includes examples and guidelines for when to use abstract classes versus interfaces.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT 4:

4: INTERFACES AND PACKAGES

Contents
4.0. Aims and Objectives
4.1. Abstract classes and Methods
4.2. Interfaces and their Purpose
4.3. Packages
4.4. Summary
4.5. Model Examination Questions

4.0. AIMS AND OBJECTIVES

This unit discusses the nature of abstract classes and methods, the purpose of interfaces
and when to use them, interface declarations and implementations and finally introduction
to packages.
After you have studied this unit, you will be able to:

• Create and declare interfaces whenever needed


• Know the purpose of Interfaces and packages
• Understand abstract classes and methods
• Implement multiple interfaces

1
4.1. ABSTRACT CLASSES AND METHODS

Packages and interfaces are two capabilities that allow you greater control and flexibility in
designing sets of interrelated classes. Packages allow you to combine groups of classes and
control which of those classes are available to the outside world; interfaces provide a way
of grouping abstract method definitions and sharing them among classes that may not
necessarily acquire those methods through inheritance.

An abstract class is a class that is declared abstract—it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be sub classed. An abstract
method is a method that is declared without an implementation (without braces, and
followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, then the class itself must be declared abstract, as in:

public abstract class GraphicObject {


// declare fields
// declare nonabstract methods
abstract void draw();
}

When an abstract class is sub classed, the subclass usually provides implementations for all
of the abstract methods in its parent class. However, if it does not, then the subclass must
also be declared abstract.

Abstract classes are similar to interfaces. You cannot instantiate them, and they may
contain a mix of methods declared with or without an implementation. However, with
abstract classes, you can declare fields that are not static and final, and define public,
protected, and private concrete methods. With interfaces, all fields are automatically
public, static, and final, and all methods that you declare or define (as default methods) are
public. In addition, you can extend only one class, whether or not it is abstract, whereas you
can implement any number of interfaces.

2
Which should you use, abstract classes or interfaces?

• Consider using abstract classes if any of these statements apply to your situation:
o You want to share code among several closely related classes.
o You expect that classes that extend your abstract class have many common
methods or fields, or require access modifiers other than public (such as
protected and private).
o You want to declare non-static or non-final fields. This enables you to define
methods that can access and modify the state of the object to which they
belong.
• Consider using interfaces if any of these statements apply to your situation:
o You expect that unrelated classes would implement your interface. For
example, the interfaces Comparable and Cloneable are implemented by many
unrelated classes.
o You want to specify the behavior of a particular data type, but not concerned
about who implements its behavior.
o You want to take advantage of multiple inheritance of type.

An example of an abstract class in the JDK is AbstractMap, which is part of the Collections
Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap)
share many methods (including get, put, isEmpty, containsKey, and containsValue)
that AbstractMap defines.

An example of a class in the JDK that implements several interfaces is HashMap, which
implements the interfaces Serializable, Cloneable, and Map<K, V>. By reading this list of
interfaces, you can infer that an instance of HashMap (regardless of the developer or
company who implemented the class) can be cloned, is serializable (which means that it
can be converted into a byte stream, and has the functionality of a map. In addition,
the Map<K, V> interface has been enhanced with many default methods such
as merge and for Each that older classes that have implemented this interface do not have
to define.

3
Note that many software libraries use both abstract classes and interfaces;
the HashMap class implements several interfaces and also extends the abstract
class AbstractMap.

An Abstract Class Example

In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier
curves, 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 able to draw or
resize themselves; they just differ in how they do it. This is a perfect situation for an
abstract superclass. You can take advantage of the similarities and declare all the graphic
objects to inherit from the same abstract parent object (for example, GraphicObject) as
shown in the following figure.

Classes Rectangle, Line, Bezier, and Circle Inherit from GraphicObject

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

4
Each nonabstract subclass of GraphicObject, such as Circle and Rectangle, must provide
implementations for the draw and resize methods:

class Circle extends GraphicObject {


void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}

When an Abstract Class Implements an Interface

In the section on interfaces, it was noted that a class that implements an interface must
implement all of the interface's methods. It is possible, however, to define a class that does
not implement all of the interface's methods, provided that the class is declared to
be abstract. For example,

abstract class X implements Y {


// implements all but one method of Y
}

class XX extends X {
// implements the remaining method in Y
}

In this case, class X must be abstract because it does not fully implement Y, but
class XX does, in fact, implement Y.

Class Members

An abstract class may have static fields and static methods. You can use these static
members with a class reference (for example, AbstractClass.staticMethod()) as you would
with any other class.

5
Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

abstract class Bike


{
abstract void run ();
}
class Honda4 extends Bike
{
void run () {System.out.println("running safely");}
public static void main (String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Outputà running safely

If you want a class to contain a particular method but you want the actual implementation
of that method to be determined by child classes, you can declare the method in the parent
class as an abstract.

• abstract keyword is used to declare the method as abstract.

• You have to place the abstract keyword before the method name in the method
declaration.

• An abstract method contains a method signature, but no method body.

6
• Instead of curly braces, an abstract method will have a semoi colon (;) at the end.

Following is an example of the abstract method.

Example

public abstract class Employee {

private String name;

private String address;

private int number;

public abstract double computePay();

// Remainder of class definition

Declaring a method as abstract has two consequences −

• The class containing it must be declared as abstract.

• Any class inheriting the current class must either override the abstract method or
declare itself as abstract.

Eventually, a descendant class has to implement the abstract method; otherwise, you
would have a hierarchy of abstract classes that cannot be instantiated.

Understanding the real scenario of Abstract class

In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user),
and an object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about
the factory method later.

7
In this example, if you create the instance of Rectangle class, draw () method of Rectangle
class will be invoked.

abstract class Shape {


abstract void draw ();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape {
void draw () {System.out.println("drawing rectangle");}
}
class Circle1 extends Shape {
void draw (){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main (String args []){
Shape s=new Circle1();
//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}

Check your progress-1


1. What are abstract classes? Explain with example?
_________________________________________________________________________________________________
_________________________________________________________________________________________________

4.2. INTERFACES AND THEIR PURPOSES

An interface is a reference type in Java. It is similar to class. It is a collection of abstract


methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.

Along with abstract methods, an interface may also contain constants, default methods,
static methods, and nested types. Method bodies exist only for default methods and static
methods.

8
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface
need to be defined in the class.

An interface is similar to a class in the following ways −

• An interface can contain any number of methods.

• An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.

• The byte code of an interface appears in a .class file.

• Interfaces appear in packages, and their corresponding byte code file must be in a
directory structure that matches the package name.

However, an interface is different from a class in several ways, including −

• You cannot instantiate an interface.

• An interface does not contain any constructors.

• All of the methods in an interface are abstract.

• An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.

• An interface is not extended by a class; it is implemented by a class.

• An interface can extend multiple interfaces.

Java includes a concept called interfaces. A Java interface is a bit like a class, except a Java
interface can only contain method signatures and fields. A Java interface cannot contain an
implementation of the methods, only the signature (name, parameters and exceptions) of
the method. You can use interfaces in Java as a way to achieve polymorphism.

9
Java Interface Example

Here is a simple Java interface example:

public interface MyInterface {


public String hello = "Hello";
public void sayHello();
}

As you can see, an interface is declared using the Java interface keyword. Just like with
classes, a Java interface can be declared public or package scope (no access modifier). The
interface example above contains one variable and one method. The variable can be
accessed directly from the interface, like this:

System.out.println(MyInterface.hello);

As you can see, accessing a variable from an interface is very similar to accessing a static
variable in a class. The method, however, needs to be implemented by some class before
you can access it.

Implementing an Interface

Before you can really use an interface, you must implement that interface in some Java
class. Here is a class that implements the MyInterface interface shown above:

public class MyInterfaceImpl implements MyInterface {

public void sayHello() {


System.out.println(MyInterface.hello);
}
}

Notice the implements MyInterface part of the above class declaration. This signals to the
Java compiler that the MyInterfaceImpl class implements the MyInterface interface.

10
A class that implements an interface must implement all the methods declared in the
interface. The methods must have the exact same signature (name + parameters) as
declared in the interface. The class does not need to implement (declare) the variables of
an interface. Only the methods.

Interface Instances:

Once a Java class implements a Java interface you can use an instance of that class as an
instance of that interface. Here is an example:

MyInterface myInterface = new MyInterfaceImpl();

myInterface.sayHello();

Notice how the variable is declared to be of the interface type MyInterface while the object
created is of type MyInterfaceImpl. Java allows this because the class MyInterfaceImpl
implements the MyInterfaceinterface.

You can then reference instances of the MyInterfaceImpl class as instances of


the MyInterfaceinterface. You cannot create instances of a Java interface by itself. You must
always create an instance of some class that implements the interface, and reference that
instance as an instance of the interface.

Implementing Multiple Interfaces: A Java class can implement multiple Java interfaces. In
that case the class must implement all the methods declared in all the interfaces
implemented. Here is an example:

public class MyInterfaceImpl


implements MyInterface, MyOtherInterface {

public void sayHello() {


System.out.println("Hello");
}

public void sayGoodbye() {


System.out.println("Goodbye");
}
}

11
This class implements two interfaces called MyInterface and MyOtherInterface. You list the
names of the interfaces to implement after the implements keyword, separated by a
comma. If the interfaces are not located in the same packages as the implementing class,
you will also need to import the interfaces. Java interfaces are imported using
the import instruction just like Java classes. For instance:

import com.jenkov.package1.MyInterface;
import com.jenkov.package2.MyOtherInterface;

public class MyInterfaceImpl implements MyInterface, MyOtherInterface {


...
}

Here are the two Java interfaces implemented by the class above:

public interface MyInterface {

public void sayHello();


}
public interface MyOtherInterface {

public void sayGoodbye();


}

As you can see, each interface contains one method. These methods are implemented by
the class MyInterfaceImpl.

Overlapping Method Signatures

If a Java class implements multiple Java interfaces, there is a risk that some of these
interfaces may contain methods with the same signature (name + parameters). Since a Java
class can only implement at method with a given signature once, this could potentially lead
to some problems.

12
The Java specification does not give any solution to this problem. It is up to you to decide
what to do in that situation.

The following Java types can implement interfaces:

Interface Variables

A Java interface can contain both variables and constants. However, often it does not make
sense to place variables in an interface. In some cases, it can make sense to define constants
in an interface. Especially if those constants are to be used by the classes implementing the
interface, e.g. in calculations, or as parameters to some of the methods in the interface.
However, my advice to you is to avoid placing variables in Java interfaces if you can. All
variables in an interface are public, even if you leave out the public keyword in the variable
declaration.

Interface Methods

A Java interface can contain one or more method declarations. As mentioned earlier, the
interface cannot specify any implementation for these methods. It is up to the classes
implementing the interface to specify an implementation. All methods in an interface are
public, even if you leave out the public keyword in the method declaration.

Interface Static Methods

A Java interface can have static methods. Static methods in a Java interface must have
implementation. Here is an example of a static method in a Java interface:

public interface MyInterface {

public static void print(String text){


System.out.print(text);
}
}

13
Calling a static method in an interface looks and works just like calling a static method in a
class. Here is an example of calling the static print() method from the above MyInterface
interface:

MyInterface.print("Hello static method!");

Static methods in interfaces can be useful when you have some utility methods you would
like to make available, which fit naturally into an interface related to the same
responsibility. For instance, a Vehicleinterface could have a printVehicle(Vehicle v) static
method.

Interfaces and Inheritance

It is possible for a Java interface to inherit from another Java interface, just like classes can
inherit from other classes. You specify inheritance using the extends keyword. Here is a
simple interface inheritance example:

public interface MySuperInterface {

public void saiHello();

}
public interface MySubInterface extends MySuperInterface {

public void sayGoodbye();


}

The interface MySubInterface extends the interface MySuperInterface. That means, that
the MySubInterface inherits all field and methods from MySuperInterface. That then
means, that if a class implements MySubInterface, that class has to implement all methods
defined in both MySubInterface and MySuperInterface.

It is possible to define methods in a subinterface with the same signature (name +


parameters) as methods defined in a superinterface, should you find that desirable in your
design, somehow.

14
Unlike classes, interfaces can actually inherit from multiple superinterfaces. You specify
that by listing the names of all interfaces to inherit from, separated by comma. A class
implementing an interface which inherits from multiple interfaces must implement all
methods from the interface and its superinterfaces.

Here is an example of a Java interface that inherits from multiple interfaces:

public interface MySubInterface extends


SuperInterface1, SuperInterface2 {

public void sayItAll();


}

As when implementing multiple interfaces, there are no rules for how you handle the
situation when multiple superinterfaces have methods with the same signature (name +
parameters).

Inheritance and Default Methods

Interface default methods add a bit complexity to the rules of interface inheritance. While it
is normally possible for a class to implement multiple interfaces even if the interfaces
contain methods with the same signature, this is not possible if one or more of these
methods are default methods. In other words, if two interfaces contain the same method
signature (name + parameters) and one of the interfaces declare this method as a default
method, a class cannot automatically implement both interfaces.

The situation is the same if an interface extends (inherits from) multiple interfaces, and one
or more of these interfaces contain methods with the same signature, and one of the
superinterfaces declare the overlapping method as a default method.

In both of the above situations the Java compiler requires that the class implementing the
interface(s) explicitly implements the method which causes the problem. That way there is
no doubt about which implementation the class will have. The implementation in the class
takes precedence over any default implementations.

15
Check your progress-2
1. Explain the role of interfaces?
_________________________________________________________________________________________________
_________________________________________________________________________________________________

4.3. PACKAGES

A package is a mechanism to group the similar type of classes, interfaces and sub-packages
and provide access control. It organizes classes into single unit.

In Java already many predefined packages are available, used while programming.
For example: java.lang, java.io, java.util etc.

Advantages of Packages

• Packages provide code reusability, because a package has group of classes.


• It helps in resolving naming collision when multiple packages have classes with the
same name.
• Package also provides the hiding of class facility. Thus other programs cannot use
the classes from hidden package.
• Access limitation can be applied with the help of packages.
• One package can be defined in another package.

Types of Packages

There are two types of packages available in Java.


1. Built-in packages
Built-in packages are already defined in java API. For example: java.util, java.io,
java,lang, java.awt, java.applet, java.net, etc.
2. User defined packages
The package we create according to our need is called user defined package.

16
Creating a Package

We can create our own package by creating our own classes and interfaces together. The
package statement should be declared at the beginning of the program.
Syntax:
package <packagename>;
class ClassName
{
……..
……..
}

Packages, as mentioned a number of times in this chapter so far, are a way of organizing
groups of classes. A package contains any number of classes that are related in purpose, in
scope, or by inheritance.

Why bother with packages? If your programs are small and use a limited number of classes,
you may find that you don't need to explore packages at all. But the more Java
programming you do, the more classes you'll find you have. And although those classes
may be individually well designed, reusable, encapsulated, and with specific interfaces to
other classes, you may find the need for a bigger organizational entity that allows you to
group your packages.

Packages are useful for several broad reasons:

• They allow you to organize your classes into units. Just as you have folders or
directories on your hard disk to organize your files and applications, packages allow
you to organize your classes into groups so that you only use what you need for each
program.
• They reduce problems with conflicts in names. As the number of Java classes grows,
so does the likelihood that you'll use the same class name as someone else, opening
up the possibility of naming clashes and errors if you try to integrate groups of

17
classes into a single program. Packages allow you to "hide" classes so that conflicts
can be avoided.
• They allow you to protect classes, variables, and methods in larger ways than on a
class-by-class basis, as you learned yesterday. You'll learn more about protections
with packages later today.
• They can be used to identify your classes. For example, if you implemented a set of
classes to perform some purpose, you could name a package of those classes with a
unique identifier that identifies you or your organization.

Although a package is most typically a collection of classes, packages can also contain other
packages, forming yet another level of organization somewhat analogous to the inheritance
hierarchy. Each "level" usually represents a smaller, more specific grouping of classes. The
Java class library itself is organized along these lines. The top level is called java; the next
level includes names such as io, net, util, and awt. The last of these has an even lower level,
which includes the package image.

Using Packages

You've been using packages all along in this book. Every time you use the import command,
and every time you refer to a class by its full package name (java.awt.Color, for example),
you've used packages. Let's go over the specifics of how to use classes from other packages
in your own programs to make sure you've got it and to go into greater depth than we have
in previous lessons.

To use a class contained in a package, you can use one of three mechanisms:

• If the class you want to use is in the package java.lang (for example, System or Date),
you can simply use the class name to refer to that class. The java.lang classes are
automatically available to you in all your programs.
• If the class you want to use is in some other package, you can refer to that class by
its full name, including any package names (for example, java.awt.Font).

18
• For classes that you use frequently from other packages, you can import individual
classes or a whole package of classes. After a class or a package has been imported,
you can refer to that class by its class name.

What about your own classes in your own programs that don't belong to any package? The
rule is that if you don't specifically define your classes to belong to a package, they're put
into an unnamed default package. You can refer to those classes simply by class name from
anywhere in your code.

Full Package and Class Names

To refer to a class in some other package, you can use its full name: the class name
preceded by any package names. You do not have to import the class or the package to use
it this way:

java.awt.Font f = new java.awt.Font()

For classes that you use only once or twice in your program, using the full name makes the
most sense. If, however, you use that class multiple times, or if the package name is really
long with lots of subpackages, you'll want to import that class instead to save yourself some
typing.

The import Command

To import classes from a package, use the import command, as you've used throughout the
examples in this book. You can either import an individual class, like this:

import java.util.Vector;

or you can import an entire package of classes, using an asterisk (*) to replace the
individual class names: à import java.awt.*

19
Check your progress-3
1. What are packages?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
__________________________________________________

4.4. SUMMARY

In this chapter, we have tried to cover the role of interfaces and packages in OOP
implementation.

Abstract classes:

• abstract classes can’t be instantiated, only sub classed.


• other classes extend abstract classes.
• can have both abstract and concrete methods.
• similar to interfaces, but (1) can implement methods, (2) fields can have various
access modifiers, and (3) subclasses can only extend one abstract class.

Abstract methods:

• abstract method bodies must be empty (no curly braces)


• subclasses must implement the abstract class’s abstract methods

A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.

Points to Remember

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.

o It cannot be instantiated.
o It can have constructors and static methods also.

20
o It can have final methods which will force the subclass not to change the body of the
method.

Like a class, an interface can have methods and variables, but the methods declared in
interface are by default abstract (only method signature, no body).

§ Interfaces specify what a class must do and not how. It is the blueprint of the class.
§ An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move (). So it specifies a
set of methods that the class has to implement.
§ If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then class must be declared abstract.
§ A Java library example is, Comparator Interface. If a class implements this interface,
then it can be used to sort a collection.
Syntax:

interface <interface_name> {
// declare constant fields
// declare methods that abstract
// by default.
}

To declare an interface, use interface keyword. It is used to provide total abstraction. That
means all the methods in interface are declared with empty body and are public and all
fields are public, static and final by default. A class that implement interface must
implement all the methods declared in the interface. To implement interface
use implements keyword.

21
4.5. MODEL EXAMINATION QUESTIONS.
QUESTIONS.

I: True/False questions
1. A class which is declared as abstract is known as an abstract class.
2. User defined packages are already defined in java API.
3. Abstract classes are similar to interfaces.
4. If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then class must be declared abstract.
5. A method which is declared as abstract and does not have implementation is
known as an abstract method.

II: Short Answer Questions

1. Explain the role of interfaces and packages in java programming?


2. Create three interfaces, each with two methods. Inherit a new interface from the
three, adding a new method. Create a class by implementing the new interface and
also inheriting from a concrete class. Now write four methods, each of which takes
one of the four interfaces as an argument. In main(), create an object of your class
and pass it to each of the methods.

22

You might also like