Are You Feeling any difficulity while writing Core-Java Programs. Send those to me Here.

Interfaces

Interfaces

Unit Structure

6.1 Introduction
6.2 More about ‗interface‘
6.3 Access
6.4 Multiple Inheritance
6.5 Interfaces and Abstract Classes
6.6 Inheritance within interfaces
6.7 Summary

6.1 Introduction

In chapter 5 you have learnt the following concepts:


  • Abstract class, which allows you to create methods in a class without writing the code for execution of the method (implementation of the method). 
  • Inheritance through the keyword ‘extends’ which tells the machine that an (inherited) class defined is of the type of a base class. 
  • Methods in the inherited class must provide implementation. (except when the inherited class is an Abstract class as well.

Interface takes the above concepts even further. It provides a mechanism to define a class with absolutely no implementation (code for execution of a method or logic).

In this chapter you will learn more about interfaces, its syntax and use, the difference between interfaces and abstract class and when to use which.

6.2 More about ‘interface’

One or more classes can implement a defined interface



When a class implements a defined interface, it has to implement (write the code, execution logic) for all the methods defined by the interface. The class is free to define more methods if necessary.




In this example, class MP3Player implements interface MusicPlayer. Here all methods of MusicPlayer are implemented; and there is one more additional method “addMusic()”

Similarly, you could have other classes inherit from the same interface MusicPlayer. Examples –

Syntax of Interface

To define an interface, use the interface keyword instead of the class keyword.
SYNTAX:
package xxx.xxx;
interface MusicPlayer{
// Cannot have method implementations:
void on();
void off();
void play();
void stop();
MusicPlayer
MP3Player
iPod
CDPlayer
implements
Interface
Classes…
}
Points to note above:


  • A semicolon after the method definition 
  • No implementation logic in the method above 
  • Interface keyword instead of class


6.3 Access

In the above example, we’ve not defined whether the interface is public, private or protected. A private interface makes no sense. If not defined the above interface is visible in the package where the interface belongs. You can define an interface public – which means the interface is visible outside the package as well.
Methods inside the interface are public by default. So in the above example, the methods are public and visible outside of the package as well.
The class which inherits the methods must explicitly define the methods to be public.
SYNTAX:
class MP3Player implements MusicPlayer{
public void on(){
System.out.println(“the MP3 Player is ON”);
}
public void off(){
System.out.println(“the MP3 Player is OFF”);
}
public void play(){
System.out.println(“the MP3 Player is playing”);
}
public void stop(){
System.out.println(“the MP3 Player is off”);
}
}

6.4 Multiple Inheritance

In Java, there is nothing which prevents from inheriting from multiple interfaces. Since there are no implementations in the methods (code in the methods), there is no danger or overwriting any implementations between multiple interfaces.

// Multiple interfaces.

interface MusicPlayer {
void on();
void off();
void play();
void stop();
}
}
interface VideoPlayer{
void on();
void off();
void play();
void stop();
void changeContrast(int x);
void changeBrightness(int x);
}
}
class iPod implements MusicPlayer, VideoPlayer{
public void on(){
System.out.println(“the MP3 Player is ON”);
}
public void off(){
System.out.println(“the MP3 Player is OFF”);
}
public void play(){
System.out.println(“the MP3 Player is playing”);
}
public void stop(){
System.out.println(“the MP3 Player is off”);
}
public void changeContrast(int x){
System.out.println(“Constrast Changed by” + x);
}
public void changeBrightness(int x){
System.out.println(“Brightnesss Changed by” + x);
}
}


6.5 Interfaces and Abstract Classes

Interfaces are similar to abstract classes. The differences are as follows:
1. All methods in an interface are abstract. Which means all methods must be empty; no code implemented.
2. In abstract class, the methods can have code/implementation within it. Atleast one method must be abstract.
3. All properties (data fields) in an interface are static final. Properties in an abstract class need not be static final.
4. Interfaces are implemented(implements keyword); Abstract classes are extended(extends keyword)
5. Class can extend only one abstract class; where as a class can implement multiple interfaces (multiple inheritance)
6. Contractual obligation: When a class specifies that it implements an interface, it must define all methods of that interface. A class can implement many different interfaces. If a class doesn't define all methods of the interfaces it agreed to define (by the implements clause), the compiler gives an error message, which typically says something like "This class must be declared abstract". An abstract class is one that doesn't implement all methods it said it would. The solution to this is almost always to implement the missing methods of the interface. A misspelled method name or incorrect parameter list is the usual cause, not that it should have been abstract!

6.6 Inheritance within interfaces

You can add new methods to an existing interface by extending it; and adding new methods.

In the above example, please note



  • ElectronicDevices is an interface. 
  • MusicPlayer and VideoPlayer are interfaces which “extend” ElectronicDevices 
  • iPod is a class which implements MusicPlayer and VideoPlayer


So, if ElectronicDevices interface had one property – which is “powerSource”; it would be inherited by all classes which implement MusicPlayer or VideoPlayer


Example for practice:

Write a class that implements the CharSequence interface found in the java.lang package. Your implementation should return the string backwards. Select one of the sentences from this book to use as the data. Write a small main method to test your class; make sure to call all four methods. Answer 1:

// CharSequenceDemo presents a String value -- backwards.

public class CharSequenceDemo implements CharSequence {
private String s;
public CharSequenceDemo(String s) {
//It would be much more efficient to just reverse the string
//in the constructor.
this.s = s;
}
private int fromEnd(int i) {
return s.length() - 1 - i;
}
public char charAt(int i) {
if ((i < 0) || (i >= s.length())) {
throw new StringIndexOutOfBoundsException(i);
}
return s.charAt(fromEnd(i));
}
public int length() {
return s.length();
}
public CharSequence subSequence(int start, int end) {
if (start < 0) {
throw new StringIndexOutOfBoundsException(start);
}
if (end > s.length()) {
throw new StringIndexOutOfBoundsException(end);
}
if (start > end) {
throw new StringIndexOutOfBoundsException(start - end);
}
StringBuilder sub =
new StringBuilder(s.subSequence(fromEnd(end), fromEnd(start)));
return sub.reverse();
}
public String toString() {
StringBuilder s = new StringBuilder(this.s);
return s.reverse().toString();
}
//Random int from 0 to max.
private static int random(int max) {
return (int) Math.round(Math.random() * max + 0.5);
}
public static void main(String[] args) {
CharSequenceDemo s =
new CharSequenceDemo("Write a class that implements the CharSequence interface found in the java.lang package.");
//exercise charAt() and length()
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
//exercise subSequence() and length();
int start = random(s.length() - 1);
int end = random(s.length() - 1 - start) + start;
System.out.println(s.subSequence(start, end));
//exercise toString();
System.out.println(s);
}
}

6.7 Summary:

In this chapter you we learn more about interfaces, its syntax and use, the difference between interfaces and abstract class with examples. We also learn the concept of inheritance within interface.



1 comment:

  1. Learn and practice some important MCQ with answers on various categories useful for competitive exams
    http://www.gkindiaonline.com/

    ReplyDelete