Unit 4
Unit 4
AIM : The point is to separate the what to do from the how to do it.
Objective:
Understand the concept of Interface.
Understand interfaces in Java
Be able to define a class that implements an interface.
Introduction to Interfaces
Java supports the concept of Inheritance that is acquiring the properties from one
class to other class. The class that acquires properties is called "subclass", and the class
from which it acquire is called "superclass". Here, one class can acquire properties from
other class using the following statement:
class A extends B
{
---------
---------
}
But, Java does not allow to acquire properties from more than one class, which we call it as
"multiple inheritance". We know that large number of real-life applications require the
use of multiple inheritance. Java provides an alternative approach known as "interface"
to support the concept of multiple inheritance.
Defining Interface
An interface is basically a kind of class. Like classes, interfaces contain the methods
and variables but with major difference. The difference is that interface define only abstract
methods and final fields. This means that interface do not specify any code to implement
these methods and data fields contain only constants. Therefore, it is the responsibility of the
class that implements an interface to define the code for these methods.
The syntax of defining an interface is very similar to that of class. The general
form of an interface will be as follows:
interface Interface_Name
{
variable declaration;
method declaration;
Here, interface is the keyword and the Interface_Name is any valid name for interface. The
variables are declared as follows:
Note: All variable are declared as constants. Methods declaration will contain only a list of
methods without any body statement. For example:
Here is an example of an interface definition that contain two variable and one method
interface Area
{
static final double pi=3.14;
Interface Body
The interface body contains method declarations for all the methods included in the
interface. A method declaration within an interface is followed by a semicolon, but no braces,
because an interface does not provide implementations for the methods declared within it. All
methods declared in an interface are implicitly public, so the public modifier can be omitted.
An interface can contain constant declarations in addition to method declarations. All
constant values defined in an interface are implicitly public, static, and final. Once again,
these modifiers can be omitted.
Your class can implement more than one interface, so the implements keyword is followed
by a comma‐separated list of the interfaces implemented by the class.
A more general form of implementation may look like this:
{
return(pi*x*x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rec= new Rectangle();
Circle c=new Circle();
Area area;
area=rec; //reference
double a=area.compute(10,20);
System.out.println("The area of the rectangle is "+a);
area=c;
a=area.compute(10,5);
System.out.println("The area of the Circle is "+a);
}
}
output
D:\>javac InterfaceTest.java
D:\>java InterfaceTest
The area of the rectangle is 200.0
The area of the Circle is 314.0
Extending the Interfaces
Like classes interfaces also can be extended. That is, an interface can be sub
interfaced from other interface. The new sub interface will inherit all the members from the
super interface in the manner similar to the subclass. This is achieved using the keyword
extends as shown here:
interface Const
{
static final int code=501;
}
}
Output
D:\>javac MenuTest.java
D:\>java MenuTest
A Java class can only extend one Base class. Multiple inheritance is not allowed. Interfaces are
not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
We can declare variables in Java interfaces. By default, these are public, final and static. That is
they are available at all places of the program, we cannot change these values and lastly only one
instance of these variables is created, it means all classes which implement this interface have
only one copy of these variables in the memory. The below example demonstrates:
/*
This is a simple Java program about Interface.
Call this file KH_InterfaceVariables.java.
*/
interface X {
int max = 10;
}
class KH_InterfaceVariables {
public static void main(String args[]) {
Example ob = new Example();
ob.getMax();
//ob.max = 20; //uncommenting this will generate compile error
}
}
Download the code Run the code
Output:
10
As you know we cannot create objects of an abstract class, but we can create objects of an
interface. And we can refer this object to any object of a class which implements its interface.
When you call a method of the interface by using interface reference object, the method defined
in the class which implements this interface gets executed. We update our SequenceDemo
program so that it explains this concept.
In the below program, we have created a reference to interface Sequence and assigned to an
object of Twos class. When we call getNextNumber method it executes getNextNumber defined
in Twos class. As a practice for you try to create Threes class which implements Sequence
interface and use our interface reference object to call methods of Twos and Threes alternatively.
/*
This is a simple Java program about Interface.
Call this file KH_InterfaceReference.java.
*/
interface Sequence {
int getNextNumber();
int setInitialValue(int x);
void restart();
}
class Twos implements Sequence {
int start;
int val;
Twos() {
start = 0;
val = 0;
}
public int getNextNumber() {
val += 2;
return val;
}
public void restart() {
val = start;
}
public int setInitialValue(int x) {
start = x;
val = x;
return start;
}
}
class KH_InterfaceReference {
public static void main(String args[]) {
Sequence ref;
Twos ob = new Twos();
ref = ob;
System.out.println("\nStarting at 100");
ref.setInitialValue(100);
for(int i=0; i < 5; i++)
System.out.println("Next value is " + ref.getNextNumber());
}
}
Download the code Run the code
Output:
Next value is 2
Next value is 4
Next value is 6
Next value is 8
Next value is 10
Resetting
Next value is 2
Next value is 4
Next value is 6
Next value is 8
Next value is 10
Starting at 100
Next value is 102
Next value is 104
Next value is 106
Next value is 108
Next value is 110
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non-abstract Interface can have only
methods. abstract methods. Since Java 8, it can
have default and static methods also.
3) Abstract class can have final, non-final, static and Interface has only static and final
non-static variables. variables.
4) Abstract class can provide the implementation of Interface can't provide the
interface. implementation of abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to
declare interface.
6) An abstract classcan extend another Java class and An interface can extend another Java
implement multiple Java interfaces. interface only.
8) A Java abstract class can have class members like Members of a Java interface are public
private, protected, etc. by default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Let's see a simple example where we are using interface and abstract class both.
interface A{
void b();
void c();
void d();
void e()
//Creating abstract class that provides the implementation of one method of A interface
//Creating subclass of abstract class, now we need to provide the implementation of rest of the m
ethods
class T extends B{
public void a(){System.out.println("I am a");}
class Test5{
A a=new T();
a.a();
a.b();
a.c();
a.d();
}}
Applications of Interfaces in Java
Interfaces are used to implement abstraction. So the question arises why use interfaces when we
have abstract classes? The reason is, abstract classes may contain non-final variables, whereas
variables in interface are final, public and static.
Extends implements
extends is for extending a class implements is for implementing an interface
extends is for when you're inheriting from implements is for when you're implementing
a base class (i.e. extending its functionality). an interface.
extends: A derived class can extend a base implements: You are implementing a contract.
class. You may redefine the behaviour of an The class implementing the interface "has a"
established relation. Derived class "is a" base capability.
class type
This is used to get attributes of a parent class This is used to implement an interface (parent
into base class and may contain already class with functions signatures only but not
defined methods that can be overridden in the their definitions) by defining it in the child
child class. class.
Summary
An interface declaration can contain method signatures, default methods, static methods
and constant definitions. The only methods that have implementations are default and
static methods.A class that implements an interface must implement all the methods
declared in the interface.An interface name can be used anywhere a type can be used.
------------------------
Review Questions
1. Explain multilevel inheritance with the help of abstract class in your program\
2. Write a program to implement multiple inheritances.
3. What is interface? How to create it and access it? Explain with example.
4. Give a detail note on interfaces with examples.
5. How Packages differ from Interfaces? Explain it with a suitable program
6. What is the difference between an interface and an abstract class?
-------------------------
Programs related to the topics discussed in this unit>>
1. Which of these can be used to fully abstract a class from its implementation?
a) Objects
b) Packages
c) Interfaces
a) Public
b) Protected
c) private
a) import
b) Import
c) implements
d) Implements
b) Interface
c) intf
d) Intf
b) Interfaces are specified public if they are to be accessed by any code in the program
d) All variables are static and methods are public if interface is defined public
6. Which of these interface declares core method that all collections will have?
a) Set
b) Event Listener
c) Comparator
d) Collection
a) Set
b) List
c) Comparator
d) Collection
a) EMPTY_SET
b) EMPTY_LIST
c) EMPTY_MAP
Class Array
array [5 – i ] = i ;
a) 12345
b) 54321
c) 1234
d) 5432
a) Set
b) List
c) Array
d) Collection
c) The Tree Set class stores values in sorted order and ensures that the values are unique
d) The elements in the Linked Hash Map are kept in sorted order
12. Which of the following package stores all the standard java classes?
a) Lang
b) Java
c) Utile
d) Java. Packages
a) Classes
b) Interfaces
c) Editing tools
a) abst
b) abstract
c) Abstract
d) Abstract class
a) Thread
b) Abstract List
c) List
16. If a class inheriting an abstract class does not define all of its function then it will be known
as?
a) Abstract
b) A simple class
c) Static class
b) Abstract class defines only the structure of the class not its implementation
a) Java.lang
b) Java.util
c) Java.io
d) Java. System
a) Static only
b) Protected
c) private
b) A class which is implementing an interface must implement all the methods of the interface.
b) Java.util
c) Java.net
d) Java.awt
a) Maps
b) Array
c) Stack
d) Queue
a) List
b) Set
c) Sorted Map
d) Sorted List
24. Which of these methods deletes all the elements from invoking collection?
a) Clear ()
b) Reset ()
c) Delete ()
d) Refresh ()
a) A group of objects
b) A group of classes
c) A group of interfaces
Class Array
Array [5-i] = i;
System.out.print (array[i]);
a) 12885
b) 12845
c) 58881
d) 54881
a). Interfaces specifies what class must do but not how it does.
b) Interfaces are specified public if they are to be accessed by any code in the program.
a) If we derive an abstract class and do not implement all the abstract methods, then the derived
class should also be marked as abstract using ‘abstract’ keyword
b) Abstract classes can have constructors
b) Protected members are accessible within a package and inherited classes outside the package.
a) Blocking Queue
b) BlockingEnque
c) Transfer Queue
d) Blocking Queue
31. Which of the following access specifiers can be used for an interface?
a) Protected
b) Private
c) Public
32. Which of the following is the correct way of implementing an interface A by class B?
a) True
b) False
a) Public static
b) Private final
c) Public final
d) Static final
a) Method definition
b) Method declaration
d) Method name
a) Abstract
b) Static
c) final
d) private
a) The concrete class implementing that method need not provide implementation of that method
c) Compilation failure
a) Compilation failure
b) Runtime Exception
39. What happens when we access the same variable defined in two interfaces implemented by
the same class?
a) Compilation failure
b) Runtime Exception
40. Which of the following is the correct way of implementing an interface salary by class
manager?
a) If we derive an abstract class and do not implement all the abstract methods, then the derived
class should also be marked as abstract using 'abstract' keyword
Show Answer
45. How can we execute a Java class independently if it doesn't have a static main method
d. By initiating the flow in any other instance method named as main and making it final
ANSWERS
2.a 24.a
3.c 25.a
4.a 26.c
5.d 27.d
6.d 28.d
7.b 29.a
8.d 30.b
9.a 31.a
10.a 32.b
11.b,c 33.a
12.b 34.d
13.d 35.b
14.b 36.a
15.a 37.c
16.a 38.a
17.c 39.d
18.a 40.b
19.d 41.d
20.c 42.a
21.b 43.c
22.a 44.c