18.Interfaces

Tuesday, February 23, 2010 Posted by Sudarsan
Welcome back folks!

In this post we are going to discuss remaining parts of Inheritance, like abstract class, interface and final class etc.

So, let’s get started!

Abstract Classes

Now suppose we want to create a superclass wherein it has certain methods in it that
contains some implementation, and some methods wherein we just want to be overridden by its subclasses.

For example, we want to create a superclass named LivingThing. This class has certain methods like breath, eat, sleep and walk. However, there are some methods in this superclass wherein we cannot generalize the behavior. Take for example, the walk method. Not all living things walk the same way. Take the humans for instance; we humans walk on two legs, while other living things like dogs walk on four legs. However, there are many characteristics that living things have in common that is why we want to create a general superclass for this.


In order to do this, we can create a superclass that has some methods with implementations and others which do not. This kind of class is called an abstract class.

An abstract class is a class that cannot be instantiated. It often appears at the top of an object-oriented programming class hierarchy, defining the broad types of actions possible with objects of all subclasses of the class.

Those methods in the abstract classes that do not have implementation are called
abstract methods. To create an abstract method, just write the method declaration without the body and use the abstract keyword.

For example,

public abstract void someMethod();


For example take look at the fallowing example

// Abstract class Demo

/**
 *
 * @author Administrator
 */
abstract class Employee
{
    int basic=2000;
    // abstract method
    abstract void salary();
}

class Manager extends Employee
{
    //abstract method implementation in Manager class
    void salary()
    {
        System.out.println("Salary : "+basic*5);
    }
}

class Worker extends Employee
{
    //abstract method implementation in Worker class
    void salary()
    {
        System.out.println("Salary : "+basic*2);
    }
}
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Manager m=new Manager();
        System.out.println("Manager");
        m.salary();

        Worker w=new Worker();
        System.out.println("Worker");
        w.salary();
    }

}

In the above program, the method salary is an abstract method and hence class Employee is also declared as abstract. The class Manager and Worker inherit class Employee and provide implementation details for method salary.

When we compile this program we can get the fallowing output

Manager
Salary : 10000
Worker
Salary : 4000

Interfaces

An interface is a special kind of block containing method signatures (and possibly constants) only. Interfaces define the signatures of a set of methods without the body.

Interfaces define a standard and public way of specifying the behavior of classes. They
allow classes, regardless of their location in the class hierarchy, to implement common
behaviors. Note that interfaces exhibit polymorphism as well, since program may call an
interface method and the proper version of that method will be executed depending on
the type of object passed to the interface method call.

Purpose of Interfaces

We need to use interfaces if we want unrelated classes to implement similar methods. Thru interfaces, we can actually capture similarities among unrelated classes without artificially forcing a class relationship.

Another reason for using an object's programming interface is to reveal an object's programming interface without revealing its class.

As we can see later on the section Interface vs. Classes, we can actually use an interface as data type. Finally, we need to use interfaces to model multiple inheritance which allows a class to have more than one superclass. Multiple inheritance is not present in Java, but present in other object-oriented languages like C++.

In order to understand an Interface let’s go thru the example

First we need to create an interface by using interface keyword.

// Creating an Interface 

/**
 *
 * @author Administrator
 */
public interface myinterface {

    public void add(int x,int y);
    public void volume(int x,int y,int z);
}

Later we need to implement this interface in another class by using implements keyword.

// Interface Implementation

/**
 *
 * @author Administrator
 */
class Demo implements myinterface
{
    // implementing interface methods add and volume
    public void add(int x,int y)
    {
        System.out.println(" "+(x+y));
    }
    
    public void volume(int x,int y,int z)
    {
        System.out.println(" "+(x*y*z));
    }

    // Demo class method multiply
    public void multiply(int x,int y)
    {
        System.out.println(" "+(x*y));
    }
}
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        //Constructing object for Demo class
        Demo d=new Demo();
        
        d.add(10, 20);
        d.volume(1, 2, 3);
        d.multiply(10, 5);
    }

}

Interface vs. Abstract Class

The following are the main differences between an interface and an abstract class:

interface methods have no body, an interface can only define constants and an interface have no direct inherited relationship with any particular class, they are defined independently.

Interface vs. Class

One common characteristic of an interface and class is that they are both types. This means that an interface can be used in places where a class can be used.

For example,given a class Person and an interface

PersonInterface, the following declarations are valid:

PersonInterface pi = new Person();
Person pc = new Person();

However, you cannot create an instance from an interface. An example of this is:

PersonInterface pi = new PersonInterface(); //COMPILEERROR!!!

Another common characteristic is that both interface and class can define methods.
However, an interface does not have an implementation code while the class have one.

Inheritance among Interfaces

Interfaces are not part of the class hierarchy. However, interfaces can have inheritance relationship among themselves. For example, suppose we have two interfaces StudentInterface and PersonInterface. If StudentInterface extends PersonInterface, it will inherit all of the method declarations in PersonInterface.

public interface PersonInterface {
. . .
}
public interface StudentInterface extends PersonInterface {
. . .
}


Final Methods and Final Classes

In Java, it is also possible to declare classes that can no longer be subclassed. These
classes are called final classes. To declare a class to be final, we just add the final keyword in the class declaration. For example, if we want the class Person to be declared final, we write,

public final class Person
{
//some code here
}
Many of the classes in the Java API are declared final to ensure that their behavior
cannot be overridden. Examples of these classes are Integer, Double and String.

It is also possible in Java to create methods that cannot be overridden. These methods
are what we call final methods. To declare a method to be final, we just add the final keyword in the method declaration. For example, if we want the getName method in class Person to be declared final, we write,

public final String getName(){
return name;
}

Static methods are automatically final. This means that you cannot override them.
Labels:

Post a Comment