Java interface as build block

In this chapter you will learn:

  1. How to partially implement an interface
  2. How to use interface to organize constants
  3. How to extend interface

Partial interface Implementations

If a class implements an interface but does not fully implement its methods, then that class must be declared as abstract. For example:

 
interface MyInterface {
  void callback(int param);
/*  www  . j  a va  2s. c  o  m*/
  void show();
}

abstract class Incomplete implements MyInterface {
  int a, b;

  public void show() {
    System.out.println(a + " " + b);
  }

}

Variables in Interfaces

We can use interface to organize constants.

 
interface MyConstants {
  int NO = 0;/*from  w  w w  . j av  a  2s  . co  m*/
  int YES = 1;
}

class Question implements MyConstants {
  int ask() {
      return YES;
  }
}

public class Main implements MyConstants {
  static void answer(int result) {
    switch (result) {
      case NO:
        System.out.println("No");
        break;
      case YES:
        System.out.println("Yes");
        break;
    }
  }
  public static void main(String args[]) {
    Question q = new Question();
    answer(q.ask());
  }
}

The output:

Extend Interface

One interface can inherit another interface with the keyword extends.

 
interface IntefaceA {
  void meth1();/*from ww w  .  j  a v  a  2 s . co m*/
  void meth2();
}
interface IntefaceB extends IntefaceA {
  void meth3();
}
class MyClass implements IntefaceB {
  public void meth1() {
    System.out.println("Implement meth1().");
  }
  public void meth2() {
    System.out.println("Implement meth2().");
  }
  public void meth3() {
    System.out.println("Implement meth3().");
  }
}
public class Main {
  public static void main(String arg[]) {
    MyClass ob = new MyClass();
    ob.meth1();
    ob.meth2();
    ob.meth3();
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How and when to instanceof operator
  2. Syntax for Java instanceof operator
  3. Example - Java instanceof operator