Lesson: Exercise: Using Library Classes

Explore the idea of code reuse by putting commonly used functions in a class that can be shared among many projects.

Understand library classes and how they facilitate code reuse. Demonstrate how to create and use a library class.


Many times we write code that will be repeated in a single project or code that is repeated in different projects. An example of this is the code to read the touch sensor in the DriveCircle project. This code would be repeated in every project that uses a touch sensor. It can be useful to put utility code, that is code that be used in several places or several projects into classes that can be called upon whenever needed. Another benefit is if we need to change how we handle the touch sensor. If the sensor code was repeated in every project, we would need to go to every project and change the code. If we have that repeated code in a utility class, then we only need to change it in one place.

Here is an example of taking the code that handles the touch sensor in the DriveCircle project and puts it into a utility class called TouchSensor. If you have not already done it, create a new package called ev3.exercises.library. Library is just a name we selected, you could call the package utilities or tools or whatever makes sense to you. In that package create a class called TouchSensor and copy/paste this code into it:

We have created a class that handles the details of the touch sensor. Any class that uses a touch sensor can create an instance of this class and monitor the touch sensor without having to worry about the details of how the sensor is handled. Note the comments before each method. These are JavaDoc comments and Eclipse will show this information when you are working with the class in other locations.

Now lets create a new project package and class to hold the DriveCircle2 exercise shown below. This is the DriveCircle exercise that uses the new TouchSensor class instead of the original code to handle the touch sensor.

So you can see we just create an instance of the TouchSensor class and make use of it. The DriveCircle2 class is simpler and if we update the TouchSensor class, DriveCircle2 will not have to be changed in terms of the details of how Touch Sensors are handled, but it will need to be recompiled to incorporate the updated library class.


Lesson navigation: