[go: up one dir, main page]

0% found this document useful (0 votes)
32 views26 pages

Unit 4

Uploaded by

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

Unit 4

Uploaded by

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

Interfaces: Defining an interface, implementing interfaces, Nested interfaces, variables in

interfaces and extending interfaces, Multiple inheritances of interfaces, Difference between


Abstract class & Interfaces.

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:

static final type variable_name=value;

Note: All variable are declared as constants. Methods declaration will contain only a list of
methods without any body statement. For example:

return_ type method_name(Parameter_List);

Here is an example of an interface definition that contain two variable and one method

interface Area
{
static final double pi=3.14;

static final String name="Java";


void display();
}

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.

Implementing the interface

Interfaces are used as "superclasses" whose properties are inherited by the


classes. It is therefore necessary to create a class that inherits the given interface. To
declare a class that implements an interface, you include an implements clause in the
class declaration. This is done as follows:
class Class_Name implements Interface_Name {

//Body of the class


}
Here, Class_Name class, implements the interface "Interface_Name".

When implementation interfaces, there are several rules −

 A class can implement more than one interface at a time.


 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend
another class.

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:

class Class_Name extends Superclass_Name implements interface1,interface 2,interface 3


{
//body of the
class
This shows that a class can extend another class while implementing interfaces. When a
class implements more than one interface they are separated by a comma.
Example
InterfaceTest.Java

/ interface definition starts here


interface Area
{
static final double pi=3.14;
double compute(double x, double y);
}
//class definition starts here
class Rectangle implements Area
{
public double compute(double x, double y)
{
return(x*y);
}
}
class Circle implements Area
{
public double compute(double x, double y)

{
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 Interface_Name1 extends Interface_Name2


{
//Body of the
Interface_name1
}
For example MenuTest.ja
va

interface Const
{
static final int code=501;

static final String branch="CSE";


}
interface Item extends Const
{
void display();
}
class Menu implements Item
{
public void display()
{
System.out.println("The Branch code is "+code+" and the Branch is "+branch);
}
}
class MenuTest{
public static void main(String args[])
{

Menu m=new Menu(); // this contains the interfaces Item and


Const m.display();

}
}
Output
D:\>javac MenuTest.java

D:\>java MenuTest

The Branch code is 501 and the Branch is CSE

Extending Multiple Interfaces

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.

Java interface Variables

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 Example implements X {


public void getMax(){
System.out.println(max);
}
}

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

Java Interface References

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;

for(int i=0; i < 5; i++)


System.out.println("Next value is " + ref.getNextNumber());
System.out.println("\nResetting");
ref.restart();

for(int i=0; i < 5; i++)


System.out.println("Next value is " + ref.getNextNumber());

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.

Abstract class Interface

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.

2) Abstract class doesn't support multiple inheritances. Interface supports multiple


inheritances.

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.

7) An abstract classcan be extended using keyword An interface class can be implemented


"extends". using keyword "implements".

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%).

Example of abstract class and interface in Java

Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 5 methods

interface A{

void a();//bydefault, public and abstract

void b();

void c();

void d();

void e()

//Creating abstract class that provides the implementation of one method of A interface

abstract class B implements A{

public void c(){System.out.println("I am C");}

//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");}

public void b(){System.out.println("I am b");}

public void d(){System.out.println("I am d");}

//Creating a test class that calls the methods of A interface

class Test5{

public static void main(String args[]){

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.

Interfaces allow you to use classes in different hierarchies, polymorphically

It is also used to achieve loose coupling.

Extends VS. Implements

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.

A class only "extends" a class. A class can only "implement" an interface..


Likewise, an interface can extend
another interface.

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>>

Java program to demonstrate positional access operations on List interface


Write a java program to create interface.
---------------------------------------------------------------------------
Multiple Choice Questions
-----------------------------------

1. Which of these can be used to fully abstract a class from its implementation?

a) Objects

b) Packages

c) Interfaces

d) None of the Mentioned

2. Which of these access specifiers can be used for an interface?

a) Public

b) Protected

c) private

d) All of the mentioned

3. Which of these keywords is used by a class to use an interface defined previously?

a) import

b) Import

c) implements

d) Implements

4. Which of these keywords is used to define interfaces in Java?


a) interface

b) Interface

c) intf

d) Intf

5. Which of the following is an incorrect statement about packages?

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

c) All variables in interface are implicitly final and static

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

7. Which of these interface handle sequences?

a) Set

b) List

c) Comparator

d) Collection

8. Which of these is static variable defined in Collections?

a) EMPTY_SET

b) EMPTY_LIST

c) EMPTY_MAP

d) All of the mentioned

9. What is the output of this program?


Import java.util.*;

Class Array

Public static void main (String args[])

int array[] = new int [5];

For (int i = 5; i > 0; i--)

array [5 – i ] = i ;

Arrays .sort (array);

for (int i = 0; i< 5; ++i)

System .out .print (array[i]);

a) 12345

b) 54321

c) 1234

d) 5432

10. Which of this interface must contain a unique element?

a) Set

b) List

c) Array

d) Collection

11. Which of the following statements are true?

a) The Tree Map class implements the Collection interface


b) The Vector class allows elements to be accessed using the get (int offset) method

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

13. A package is a collection of

a) Classes

b) Interfaces

c) Editing tools

d) Editing tools and interfaces.

14. Which of these keywords are used to define an abstract class?

a) abst

b) abstract

c) Abstract

d) Abstract class

15. Which of these is not abstract?

a) Thread

b) Abstract List

c) List

d) None of the Mentioned

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

d) None of the mentioned

17. Which of these is not a correct statement?

a) Every class containing abstract method must be declared abstract

b) Abstract class defines only the structure of the class not its implementation

c) Abstract class can be initiated by new operator

d) Abstract class can be inherited

18. Which of these packages contains abstract keyword?

a) Java.lang

b) Java.util

c) Java.io

d) Java. System

19. the fields in an interface are implicitly specified as,

a) Static only

b) Protected

c) private

d) Both static and final

20. Which of the following is not true?

a) An interface can extend another interface.

b) A class which is implementing an interface must implement all the methods of the interface.

c) An interface can implement another interface.

d) An interface is a solution for multiple inheritances in java.

21. Which of these packages contain all the collection classes?


a) Java.lang

b) Java.util

c) Java.net

d) Java.awt

22. Which of these classes is not part of Java’s collection framework?

a) Maps

b) Array

c) Stack

d) Queue

23. Which of this interface is not a part of Java’s collection framework?

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 ()

25. What is Collection in Java?

a) A group of objects

b) A group of classes

c) A group of interfaces

d) None of the mentioned

26. What is the output of this program?


Import java.util.*;

Class Array

Public static void main (String args[])

Int array [] = new int [5];

For (int i = 5; i > 0; i--)

Array [5-i] = i;

Arrays. fill (array, 1, 4,8);

For (int i = 0; i < 5; i++)

System.out.print (array[i]);

a) 12885

b) 12845

c) 58881

d) 54881

27. Which of the following is incorrect statement about packages?

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.

c) All variables in interface are implicitly final and static. d)


All variables are static and methods are public if interface is defined public.

28. Which of the following is FALSE about abstract classes in Java

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

c) A class can be made abstract without any abstract method

d) A class can inherit from multiple abstract classes.

29. Which of the following is true about inheritance in Java?

a) Private methods are final.

b) Protected members are accessible within a package and inherited classes outside the package.

c) Protected methods are final.

d) We cannot override private methods.

30. Which of the below is not a sub interface of Queue?

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

d) Public, protected, private

32. Which of the following is the correct way of implementing an interface A by class B?

a) Class B extends A{}

b) Class B implements A{}

c) Class B imports A{}

d) None of the mentioned

33. All methods must be implemented of an interface.

a) True
b) False

34. What type of variable can be defined in an interface?

a) Public static

b) Private final

c) Public final

d) Static final

35. What does an interface contain?

a) Method definition

b) Method declaration

c) Method declaration and definition

d) Method name

36. What type of methods interfaces contain by default?

a) Abstract

b) Static

c) final

d) private

37. What will happen if we provide concrete implementation of method in interface?

a) The concrete class implementing that method need not provide implementation of that method

b) Runtime exception is thrown

c) Compilation failure

d) Method not found exception is thrown

38. What happens when a constructor is defined for an interface?

a) Compilation failure

b) Runtime Exception

c) The interface compiles successfully


d) The implementing class will throw 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

c) The JVM is not able to identify the correct variable

d) The interfaceName.variableName needs to be defined

40. Which of the following is the correct way of implementing an interface salary by class
manager?

a) Class manager extends salary {}

b) Class manager implements salary {}

c) Class manager imports salary {}

d) None of the mentioned

41. Which of the following is FALSE about abstract classes in Java

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

c) A class can be made abstract without any abstract method

d) A class can inherit from multiple abstract classes

42. Which of the following is used to make an Abstract class?

a) Making at least one member function as pure virtual function

b) Making at least one member function as virtual function

c) Declaring as Abstract class using virtual keyword

d) Declaring as Abstract class using static keyword

43.We can make a class abstract by

a) Declaring it abstract using the virtual keyword


b) Making at least one member function as virtual function

c)Making at least one member function as pure virtual function

d) Making all member function const

44. Interface can only have...

a. Member elements and Methods.

b. Static Variables and Static Methods.

c. Static Final Variables and Instance Method Declarations.

d. Member Elements, Instance Methods, Static variables and Static Methods.

Show Answer

45. How can we execute a Java class independently if it doesn't have a static main method

a. By initiating the flow in any of the static method

b. By initiating the flow in any of static block

c. By initiating the flow in any other instance method named as main

d. By initiating the flow in any other instance method named as main and making it final

ANSWERS

1.c 23.d 45.b

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

You might also like