Tag Archives: tutorial

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.

Advertisements

Java is object oriented.

I’ve gone a long way, to start to understand the idea behind design of java. And as i grasped its caveeats, like interfaces and abstracts classes, i discovered for myself how genious java actually is.

Everything is an object. I tend to call Java a real world modelling language. One who want to understand java has better to throw all his knoweledge of Pascal or any other procedural language programming  over board. Java is another way of thinking, another way of program design. Its like you would add a third dimension to the existing two.

Every object of the real world has  some properties, und usually you can do something with it.

The pen, has color, length, and maybe a price, it has certain geometric form, it can be translucient, be disposable or not, use ink or be a gel pen and so on. And when we say, „I need a pen“  we usually have a distinct picture in mind, but what we really mean can be any kind of a pen, with any set of attributes. We recognize a pen, if it has some of the typicall attributes of a pen. In terms of java language, we say that a pen is a class, and any certain pen which really exists , is an object of the class „pen“. A Java Class does describe the attributes of our imaginary object, and we create the  objects by instantiating the class.

Lets look at an example:

public class pen

{

int length;

int width;

double inklevel;

}

that’s it,  one possible implementation of pen in java. But to use our pen further in the program, we have to assemble those attributes to an object. That is what we call „to make an instance of a class“.  When we create an object of a class, the space is allocated in the memory for all attributes/variables, which the object contain. But you are not limited to only one object, you can create as much as you want. Its important to understand, that if we create one object from the pen class and after that a second one, they are not the same – they differ, even though all their attributes may contain same values.

Lets create a main class, where we can create an instance of the pen.

public class Main // [1]

{

public static void main(String [] args) // [2]

{

pen p = new pen(); //[3]

}

}

Okay, what we did, we created a new class, called Main. Its a common practice, to call the Class Main, because this is one where all the program  management  happens. Its a good idea, to give the classes such names, which reflect their role or intention. Its important to notice, the name of the class has to be written „Main“ and not „main“, because in such a case, the java compiler will think of an main() method inside, as of a constructor, and not a start-up statement. What are constructors  ? Constructors, are special methods which are used to initialize the objects attributes with values at the moment of their creation. This can be very useful. The constructor method has to have exactly the same name as the class itself, and to be declared as public. The word public declares that other classes and parts of the programm  have free access to it. The access management in java programs is one of the powerful concepts, which make java to be spoken of as a  secure language. Back to constructors. Through defining several different constructors you may make sure that an object will have certain attributes initialized at the moment of creation. The constructor methods of the same class differ in the attributes they need for the execution.

Lets add some constructors to our pen class.

public class pen

{

int length;

int width;

double inklevel;

public pen(){}  //[4]

public pen(int length){this.length = length } //[5]

public pen(int le, double ile){length = le; this.inklevel = ile; } //[6]

}

Now, we have three different constuctors for our pen class. The fisrt one is called default constructor , we dont have excpicitely to write it, because if we dont define any default constructor at all , java compiler creates one for us. Default constructor is called in case we didnt specified any special values we would like to pass to our object at the moment of creation. What does the word „this“ @[5] mean, you may ask. The word „this“ indicates the one object which variable is meant. I gave the attribute of the constructor here the same name, as the instance variable. if we dont indicate the variable we want to use, explicitely, the compiler wouldn’t know which one we are actually meaning, the „length“ variable passed to the constructor, or the one belonging to the object. To avoid such misunderstanding we indicate with specials word „this“ that we want to assign the value of the passed variable to the „length“ variable of our object . You can certainly, avoid such thing simply by using differend variable names, as i did @ [6].

In our Main  class we called the default constructor @ [3] Lets add another constructor, for the case we want to create a pen with a certain length.

public class Main

{

public static void main(String [] args)

{

pen p = new pen();

pen p1 = new pen ( 23 ); // [7]

}

}

We passed an integer value to the constructor @ [7]. The compiler knows which constructor to use, because there is only one constructor which accepts an integer value, the one @ [5]. Thats why you shouldnt define two constructors which have same signature (combination of the name and accepted attributes ).The compiler wouldnt just know which one to pick.

We can acces the values of the intance variables in our two objects, to do this we just tell which object we want to use , and put a point sign after it, then we write the variable name we want to use. We can  assign the „length“ value for our pen object „p“. So we write

public class Main

{

public static void main(String [] args)

{

pen p = new pen();

pen p1 = new pen ( 23 );

p.length = 16; // [8]

System.out.println(p.length); //[9]

}

}

Now the length of the pen „p“ is set to 16 units. We can send the value of the „length“ variable of  „p“-object to the system output device (usually the console or command line) as we do in line @[9]. But what if we dont want that any other classes can set, reset, and call the values of the instance variables. We can prohibit public access to  it, by putting the word „private“ before it. So the pen class would look like this

public class pen

{

private int length;

int width;

double inklevel;

public pen(){}

public pen(int length){this.length = length }

public pen(int le, double ile){length = le; this.inklevel = ile; }

}

So now only the methods which are declared inside the class may have full access  to the variable „length“.

Okay enough for the first time… write me if you wish more examples or more explanation on particular point.

Any suggestions and hints are warmly appreciated.

Next time i wish to wite about interfaces, and why you should use them, and i will come along with some more interesting example for the classes than a pen.

Think in Objects!

So long, A.S.