More Java. Continued.

Last time we worked out an implementation of a simple thermometer software in java. I promised to add  an interface to it and to show you that you can provide it some nifty methods, to make your thermometer more powerful. So lets begin.

First of all, let me explain the use of interface classes in Java. The need for an interface doesnt seem to be quite obvious in some cases. An interface is a declaration of some certain, obligatory behaviour. We know that behaviour in java is defined through methods, methods describe how to perform this or that action. We also know, that classes can inherit from their parents, those things they have in common. A bus can inherit from vehicle, and tea can be a child-class of a HotDrinks class. A notebook is a child of a computer, and so forth. But what do we do, if we want a certain class present some features which are not typical for this sort of objects. I mean, for instance,  what if you want a tree class which  probably extends the plant class, not only to perform grow method but also do something untypical, like walk over the ground, and speak. Yes, lets assume you want make your plants  to be units of some simulation or strategy game, so they have to speak, und to walk. To speak and to walk taken together is an characteristic of a human being. But even if we do create a Human class, we still cant inherit from it, because java doesnt support multiple inheritance. Java goes another way here, providing us a tool, called interface, to satisfact all our polymorphing needs. So we create an Interface, lets call it  isHuman.

An interface does only provide the declarations of methods, and never provides their implementation. Interfaces can also contain constans. Constans will be common to all classes which implement the interface. Its important to know that you can implement as many interfaces as you like, to provide the desired bahavior to your object. So, here is what the isHuman interface could look like:

interface isHuman{

public speak(String message);

public walk(int distance);

}

and our Tree class would implement this interface and look something like:

class Tree extends Plant implements isHuman {

public void speak(String message){ System.out.printline(message); }

public void walk(int distance){

/* consider that moving the tree around will change its position, or its coordinate. But a nor the plant class nor his tree subclass do define any  class variables  to save coordinates. So we would probably like to attach a position variable to the tree class. On the other hand it would be better object oriented desing, if we wouldnt  put litter into pure classes, so we should subclass the Tree class (i.e. MagicTree) and  provide MagicTree with  position variable and let it implement the isHuman interface*/

} }

Enough explanation to take off. Lets now provide our thermometer some interface. What would we like our thermometer to do, something which is not common to all thermomethers ? Our thermometer will have a display built in, which should show the registered temperature.So let’s define an Interface hasDisplay. Every device which has a display, have probably two actions in common, it can display something and reset the display. So here we go:

public interface hasDisplay {

void display();

void reset();

}

The other thing, we would like to teach our thermomether is to perform statistics onto collected data. For expample, to calculate average of all gathered values. So lets define an interface:

public interface supportsStatistics {

double getAverage();

}

So lets put these methods into our Thermometer class.It looks  now as follows:

import java.util.Stack; //Stack is good for collecting values

import java.util.Iterator; //Is a useful class to walk through the data of a stack

public class thermometer implements hasDisplay, supportsStatistics{

boolean isApplied;

Stack s; // Our thermometer has a memory, represented through the stack here.

sensor sen;


private void apply()

{

if (isApplied == false) isApplied=true;

}

double getTemperature()

{

this.apply();

return this.sen.getLevel();

}

void remove(){ isApplied = false; }

public void reset(){};

public void display()

{

System.out.println(new Double(this.getTemperature()).toString());

/* Create an Object of type „Double“ from the value,returned through getTemperature method. The Method toString,  built in into Double class, returns a String representation of the Double object in turn, which becomes an argument of a println method. */

}

public void display(double d)

{ /* this one can show any double value you pass to it*/

System.out.println(d);

}

/* Methods for memory handing */

void pushValueToStack()

{

Double d = Double.valueOf(this.getTemperature());

s.push(d);

System.out.println(“ [ „+ s.peek() + “ pushed ]“);

}

double retrieveValueFromStack()

{

return Double.valueOf( s.pop().toString() );

}

public double getAverage()

{      double av=0.0;

int c=0;

Iterator it = s.iterator();

while(it.hasNext())

{    c++;

System.out.println(„sum = „+av);

av=av+Double.valueOf( it.next().toString() );

}

return av/c;

}


public thermometer(){ // Constructor

this.s = new Stack();

this.sen = new sensor();

}

}

Now we have implemented an interface and provided our thermometer with a possibility to store, and process values. Quite useful, isn’t ist ? Now let me try to answer the last question about interfaces:

„Doesnt it look like, when one implements an interface he has to write the method declarations twice ? First time in the Interface, and the second time inside the class. Why not ommit the Interface and add desired methods rigth into the class, without any interface-bla-bla.“

The answer is quite simple: „Sure, you are free to do so, but imagine you have project which contains hundreds of classes, and you would add some behavior here and some behaviour there, without using the interfaces. Nobody else but you would then know, what special abilities can the class use. By declaring interfaces, and using them consistently inside your project, helps you get better picture of the possibilities, dependencies and duties of every single class. Interfaces is an object oriented design tool. Nobody forces you to use it. But by doing so you profit in the long run.

Thank you for your attention.

P.S: If you have  wishes or questions , feel free to leave a comment.

So long, A.S.