Tag Archives: object

More Java (basic part)

Today i would like to introduce you a more complex example for java. We will program a piece of software for a thermometer. Lets imagine we would have a microcontroller which is able to get the temperature and put it in some system variable. And we would have a possibility to access this system variable, representing the current temperature. In fact we will emulate this system variable simply by a random number generator. But there are Java microcontrollers in real life, so the whole piece of software which we are going to write is not far from reality.

Let’s start then. First of all we need to think about the Class structure for our thermometer.We obviously need a Class thermometer , which will represent a thermometer. In addition we will create a class sensor which will represent a sensor integrated inside the thermometer. As we will step through the creation process we will need some more classes, for the purpose of better object oriented design.

For now lets write the Thermometer class.  A thermometer has, as such a state which describes if it is applied or not. Having a boolean isApplied variable lets us check wether the thermomeer is applied. We can apply it if it is not applied. So we can only get temepature value from our device in case it is applied. This describes the real world situation precisely enough. Lets look at the code:

class Thermometer {

boolean isApplied;

}

Our Thermomether has a sensor, so lets put a sensor inside our thermomether class.

class Thermometer {

boolean isApplied;

Sensor sen;

}

Well variable sen has type of Sensor , but there is no such built-in class in Java library called „sensor“. Of course not. We will create the Sensor-Class. So lets create a new file Sensor.java and think about properties of a sensor. Sensor can be active or not, so we define a boolean variable isActive. A sensor has a level, its the amount of signal is measures. It doesnt matter if it measures temperature, pressure, velocity, distance or amplitude, a sensor only gives back some numeric value. So we define a level variable of type double.

Here is our Sensor.class

public  class sensor {

private double level;
private boolean active;

}

why is the level variable defined as private. It has a good reason. We will define a special initalization routine for the sensor later, and only this initialisation procedure (method) has the right to access the value of the level variable. If some other class would like to use our Sensor class, it couldnt just create an instance of a Sensor, and then write something like mysensor.level = 123.45. He would be forced to use the special method provided by the Sensor class,to access the value of the level variable. Lets now write the methods to acess the instance variables for the Sensor class. First a method which sets our sensor to the active state.

public void setActive(){

this.active = true;

}

Now the method which returns the sensor level. Forst of all we set the Sensor to the active state, and use the method setActive we defined before. After this we have to run the initialization. We will define the initialization procedure in the init() method. init() returns zero if the initalization went sucessful. So we check if the initialization was sucessful and want to process an exceptional state which occurs if the program flow goes in a way it is not intended to go. We throw an exception. There are many exceptions defined inside the java library, but we create our own exception here. It will inherit from the Exception class. The catch block contains the code, which will be executed if the exception, we were afraid of, occurs.

Then we assign a random value to the level variable, and return this value, to the caller object.

public double getLevel()
{
try
{
this.setActive();
this.init();
if (this.init()!=0) throw new badSensorException();
this.level = Math.random()*100;
return level;
}

catch (badSensorException e)
{
System.out.println(„Error occured!“+e);
}

return this.level;

}

Okay, lets look deeper iside these exceptions. An exception is an object too. An exception is created, and passed as a paramether to to handling procedure, the catch procedure. Here is class for the badSensorException

public class badSensorException extends Exception{

badSensorException(){};
}

as i said before, all user defined exceptions inherit form the standart library class Exception. The only line inside the class is the default constructor. Exceptions are objects and need to be created, like all other objects. Nothing special.

later on in the sensor class we define the init() method. Here is what it looks like:

private int init() throws badSensorException
{
return 0;
}

The method is a dummy method. It do just return Zero, like if it would all go flawlessly and correctly. But take a look at the declaration. We do provide the compiler the information, that the execution of this method, may lead to an exceptional state.  So lets sum up, if we know that something in  a method can go the way we dont want it to, we declare that this method throws someException, then we we write a class for someException which extends the Exception class. An then every time we have to use a method which is capable of throwing an exception, we put it inside the try-block  and then we handle the exeptional state within the corresponding catch -block. Thats it.

finally we have to create a constructor for our sensor. here is what it looks like.

public sensor()
{
try
{
if (this.init()!=0); throw new badSensorException();
}
catch (badSensorException e){
System.err.println(e.getMessage());}
}

As we can see, creating a sensor incudes an obligatory initalization procedure. Which requires exception handling, since, the init() mehtod is capable of throwing an exception. Our Sensor Class is complete now. Feel free to add some more methods, which you consider useful, like  a reset() or deactivate() or whataever.

Here is what the complete Sensor.class looks like:

public  class sensor {
private boolean active;
private double level;
public void setActive() {  this.active = true;  }
public double getLevel()
{
try
{
this.setActive();
this.init();
if (this.init()!=0) throw new badSensorException();
this.level = Math.random()*100;
return level;
}

catch (badSensorException e)
{

System.out.println(„Error occured!“+e);
}

return this.level;

}

private int init() throws badSensorException
{
return 0;
}

public sensor()
{
try
{
if (this.init()!=0); throw new badSensorException();
}
catch (badSensorException e)

{
System.err.println( e.getMessage() );

}
}

}

Lets now return to our thermometer class.That what it looked like.

class Thermometer {

boolean isApplied;

Sensor sen;

}

So first of all we write a method to apply the thermometer.

private void apply()
{
if (isApplied == false) isApplied=true;

}

Lets now look at the constructor for the thermomether. We just create a new sensor inside every thermometer, thats it.

public thermometer(){
this.sen = new sensor();
}

You recall,  by writing this.sen we mean the sen variable of this object. Now  lets define a method which will get the temperature from the thermometer. Here it is:

double getTemperature()
{
this.apply();
return this.sen.getLevel();
}

the method returns the value, provided by the level variable of the Sensor object.

this.sen.getLevel() means: „call the getLevel() method of the sen object, which is defined inside this thermomether object“. Before we can call getTemperature() method, we have to create an instance of Thermometer class. Creating this, we automatically create an instance of Sensor, this is  defined inside the constructor. So every Thermometer object knows a Sensor object, which belongs to it. By calling this.sen.getLevel() you tell that we want to use the Sensor of  this thermomerter, not one other’s.

Finally lets write a display method. It will send the temperature values to any output device, we provide. For our example we will use the console for output.

public void display()
{
System.out.println(new Double(this.getTemperature()).toString());

}

The System.out.println() method accepts a string value as a parameter, and we want it to print a double value. So we have to convert the double value to String. Every object which inherits from the Object has access to the toString() method.It returns a String representation of the object its called on. The temperature values are of Type double. It is a primitive type. Primitive types are not objects, so we cant use all the power of objects on them. But Java instroduces a nice concept to help out.  The wrapper classes. Wrapper class is a corresponding Object Type for every Primitive type. So there is Integer wrapper class  corresponding to int, and Double corresponding  to double. But we know, objects have to be created. Every wrapper class has plenty of  constructor methods, there is also one constructor, to create an Object from the corresponding primitive type. The signature of such a constructor looks like this Double(double d).  So we call the constructor for Double, passing  the return value of the getTemperature() of this object to it.

new Double(this.getTemperature()) returns an Object of Double, Having an Object we can  call to the toString() method on it. so we simply attact a method call to our newly created Double object. toString has a return type of String. This whole strange looking performance is called casting. We cast a variable form one type to other.

Now the basic implementation for  our Thermomether class is complete. Here is what it looks like:

public class Thermometer {

boolean isApplied;
Sensor sen;

private void apply()
{
if (isApplied == false) isApplied=true;
}
double getTemperature()
{
this.apply();
return this.sen.getLevel();
}

public void display()
{
System.out.println(new Double(this.getTemperature()).toString());

}

public Thermometer()

{
this.sen = new sensor();
}

}

Now we do have a Sensor class, a Thermomether Class which uses the Sensor class , the last thing we will need is a main method to start everything up. Here we have two possibilites. The first is to make an extra class file, where the main function will reside, und the second is to place the main method inside our Thermometer class.

I wanted to write about using of interfaces. but did intentionally reduced the code. It would otherwise be hard to keep a track of all dependencies betwenn the classes.

Lets summarise, what we have done today. We created three classes, we learned the use of private variables, we used exception handling, we did a type casting, and learned about wrapper classes. Pretty much for one session.

The next time we will attach an interface to our class and  add some new interesting and useful functionality to our thermometer class.

Think in objects !

So long,   A.S

Advertisements