[Java] [ev3×Java] Interface, implementation and inheritance (event processing)

7 minute read

In this article, we will mainly look at the function called interface using a robot.

table of contents

  1. What is an interface?
  2. Code structure 1-0. Sample code that implements processing in the interface 1-1. Sample code that creates a class and implements an interface
  3. Sample code of interface TimerListnener and implementation class Timer
  4. Relationship between motor class and interface in leJOS

0. What is an interface?

An interface is like a class that defines a method specification only. Although the methods are arranged in the interface, the process is not written.

So when you look at a method, you can see what it does, but not what it actually does. You can see the contents of the method processing by looking inside the **class that implements the interface.


Point: Interface Define only method specifications (return value, method name, arguments) Do not actually process


Point: Class that implements the interface Define the contents of method processing Do the work


[Reference article] Implement interface! How to use implements in Java *As described here, there is also implementation of method processing in an interface.


1. Code structure

1-0. Sample code to implement the process in the interface

First, let’s look at the following code. It is a program that displays characters at the start and end of motor rotation.

MotorEvent.java


import lejos.hardware.motor.EV3LargeRegulatedMotor;
import lejos.hardware.port.MotorPort;
import lejos.robotics.RegulatedMotor;
import lejos.robotics.RegulatedMotorListener;
import lejos.utility.Delay;

public class MotorEvent{
It's a sequel.
// create an instance
//RegulatedMotor: Interface
//EV3LargeRegulatedMotor: class that implements the interface
private static RegulatedMotor l_a = new EV3LargeRegulatedMotor(MotorPort.A);
It's a sequel.
public static void main(String[] args) {
It's a sequel.
// create an instance
//Customize the method in the interface RegulatedMotorListener and define the process
final RegulatedMotorListener listener = new RegulatedMotorListener() {
It's a sequel.
//Customize the following two methods of the interface RegulatedMotorListener
It's a sequel.
// Customize the method that will be called when the motor starts spinning
@Override
public void rotationStarted(
final Regulated Motor motor,
final int tachoCount,
final boolean stalled,
final long timeStamp) {
// What to customize
System.out.println("Started");
Delay.msDelay(500);
}
// Customize the method that will be called when the motor stops spinning
@Override
public void rotationStopped(
final Regulated Motor motor,
final int tachoCount,
final boolean stalled,
final long timeStamp) {
// What to customize
System.out.println("Stopped");
Delay.msDelay(500);

}
It's a sequel.
};
It's a sequel.
//addListener method takes an instance of RegulatedMotorListener
//If there is any movement in the motor, it will be reported to the listener
// and the method in listener is called
l_a.addListener(listener);
l_a.forward();
Delay.msDelay(2000);
l_a.stop();
Delay.msDelay(500);
It's a sequel.
}
}

Sample code overview

  1. I want to use addlistener method to display characters at the start and end of motor rotation**. *Void addListener (RegulatedMotorListener listener) Adds a listener object that’s notified when rotation starts or stops

  2. The addlistener method is implemented in the class EV3LargeRegulatedMotor, so create a reference type variable l_a from it and use it in the form l_a.addlistener**.

  3. Also, the addlistener method takes an instance of the interface RegulatedMotorListener** as an argument, so it is necessary to first create an instance from that interface**.

  4. However, the interface does not define the method processing , so even if an instance is created ** it cannot actually be processed **. Therefore, **Customize the method in the interface and define the processing so that the processing can be performed.


Sample code organization

◯ Interface: Regulated Motor Implementation class: EV3LargeRegulatedMotor

◯ Interface: RegulatedMotorListener Implementation class: None (implemented in the interface)

◯ Method: rotationStarted() Only specification is defined in RegulatedMotorListener Method called when the motor starts rotating

◯ Method: rotationStopped() Only specification is defined in RegulatedMotorListener Method called when the motor finishes rotating

◯ Method: addlistener() void addListener(RegulatedMotorListener listener) Takes the object created from the interface as an argument. The specification is defined in the interface RegulatedMotor and implemented in the EV3LargeRegulatedMotor class.


1-0. Sample code to create a class and implement an interface

◯ Create a class named RotateStateEvent to implement the interface RegulatedMotorListener. In it, customize the method in RegulatedMotorListener to define the processing.

MotorEvent02.java


import lejos.hardware.motor.EV3LargeRegulatedMotor;
import lejos.hardware.port.MotorPort;
import lejos.robotics.RegulatedMotor;
import lejos.robotics.RegulatedMotorListener;

public class MotorEvent02 {

    private static RegulatedMotor l_a = new EV3LargeRegulatedMotor(MotorPort.A);

    public static void main(String[] args) {
        // Use an instance of class RotateStateEvent as an argument
        l_a.addListener(new RotateStateEvent());
        l_a.forward();
        Delay.msDelay(2000);
        l_a.stop();
        Delay.msDelay(500);
    }
}

// Create a class that implements the interface RegulatedMotorListener
class RotateStateEvent implements RegulatedMotorListener{
    @Override
    public void rotationStarted(
                    final Regulated Motor motor,
                    final int tachoCount,
                    final boolean stalled,
                    final long timeStamp) {
                // define the process
                System.out.println("Started");
                Delay.msDelay(500);
            }

    @Override
    public void rotationStopped(
                    final Regulated Motor motor,
                    final int tachoCount,
                    final boolean stalled,
                    final long timeStamp) {
                // define the process
                System.out.println("Stopped");
                Delay.msDelay(500);
                }
}



Point: implements

It can be defined as a class that implements the interface in the form of class implements interface {}.


2. Sample code of interface TimerListnener and implementation class Timer◯ Create the SecondCounter class by yourself to handle the Timer class.

The Timer class takes an instance of the TimerListener interface (the class that implements) as an argument. Then, every specified cycle, the timedOut method (=process) in the TimerListener interface (the class that implements) is called.

This time, the program counts every 1 second, displays it, and makes a sound every 5 seconds.

.java


import lejos.utility.Timer;
import lejos.hardware.Sound;
import lejos.utility.TimerListener;

public class SecondCounter {
    private int second;

    // Generate an interrupt every 1000 milliseconds
    private Timer timer = new Timer(1000, new CountTimer());

    public void reset() {
        second = 0;
    }

    public int getSecond() {
        return second;
    }

    public void start() {
        timer.start();
    }

    public void stop() {
        timer.stop();
    }
    //Create a CountTimer class that implements the interface TimerListener
    class CountTimer implements TimerListener {
        // Every 1000 milliseconds, the timedOut() method is called by Timer
        //Customize and define the processing contents of the method in the interface
        @Override
        public void timedOut() {
            // increment by 1
            second++;
            System.out.print(second);
            / Make a sound every 5 seconds
            if(second %5 == 0 ){
            Sound.beep();
            }
        }
    }
}

.java


import lejos.hardware.Button;
import lejos.hardware.motor.EV3LargeRegulatedMotor;
import lejos.hardware.port.MotorPort;
import lejos.robotics.RegulatedMotor;
import lejos.utility.Delay;

public class SecondCounterSample {
It's a sequel.
    private static RegulatedMotor l_a = new EV3LargeRegulatedMotor(MotorPort.A);

    public static void main(String[] args) {
        
        //// Creating an instance of the class SecondCounter defined above
        SecondCounter counter = new SecondCounter();
        // start counting
        counter.start();

        //20 repeat the process
        for (int i = 0; i <20; i++) {
        It's a sequel.
            if(i == 10) {
            // reset the timer
            System.out.print("reset ");
            counter.reset();
            }else if(i >15) {
            // Drive slowly
            System.out.print("slowdown ");
            l_a.setSpeed(100);
            }else {
             //To accelerate
            // set speed to count *100
            l_a.setSpeed(counter.getSecond() * 100);
            }
            l_a.forward();
            Delay.msDelay(1000);
        }
        l_a.stop();
        counter.stop();

        System.out.println("push any button");
        Button.waitForAnyPress();
    }

}

Point: public Timer(int theDelay,TimerListener el) Takes an instance of the cycle and TimerListener class (class that implements).

Point: void timedOut() Called every time the Timer fires. Called every time the Timer fires

3.leJOS relationship between motor class and interface

Let’s look at the relationship between classes and interfaces related to motors.

Class BaseRegulatedMotorClass EV3 Large Regulated Motor * Interface Regulated Motor * Interface BaseMotor

The largest group of motors is the class BaseRegulatedMotor, which the EV3LargeRegulatedMotor inherits. The interface RegulatedMotor is implemented in these two classes. It also inherits the interface BaseMotor.


###** Class BaseRegulatedMotor**

◯ Implements the following interface BaseMotor,RegulatedMotor…

◯ Subclass EV3LargeRegulatedMotor, EV3MediumRegulatedMotor…

BaseRegulatedMotor.java


//Excerpt of a part of BaseRegulatedMotor class
public abstract class BaseRegulatedMotor extends Device implements RegulatedMotor{

    public void forward()
    {
        reg.newMove(speed, acceleration, +NO_LIMIT, true, false);
    }

    public void rotate(int angle, boolean immediateReturn)
    {
        rotateTo(Math.round(reg.getPosition()) + angle, immediateReturn);
    }

    public void addListener(RegulatedMotorListener listener)
    {
        reg.addListener(this, listener);
    }
    
    public RegulatedMotorListener removeListener()
    {
        return reg.removeListener();
    }

    ...

}

Point: Inheritance You can extend classes using extends.

[Reference article] extends keyword


Point: implements

It can be defined as a class that implements the interface in the form of class implements interface {}.


###Class EV3 LargeRegulatedMotor

◯ Implements the following interface Interface: BaseMotor, Encoder, RegulatedMotor, Tachometer

EV3LargeRegulatedMotor.java


//EV3LargeRegulatedMotor class which inherits BaseRegulatedMotor class
public class EV3LargeRegulatedMotor extends BaseRegulatedMotor
{
    public EV3LargeRegulatedMotor(Port port)
    {
        super(port, null, EV3SensorConstants.TYPE_NEWTACHO, MOVE_P, MOVE_I, MOVE_D,
                HOLD_P, HOLD_I, HOLD_D, OFFSET, MAX_SPEED);
    }

    ...
}

###** Interface RegulatedMotor**

◯ Implemented in the following class BaseRegulatedMotor, EV3LargeRegulatedMotor, EV3MediumRegulatedMotor…

◯The interface BaseMotor is inherited

.java


// excerpt from interface RegulatedMotor
public interface RegulatedMotor extends BaseMotor, Tachometer, Closeable {

public void addListener(RegulatedMotorListener listener);

    public RegulatedMotorListener removeListener();

    void rotate(int angle, boolean immediateReturn);

    public void stop(boolean immediateReturn);

    ...


###** Interface BaseMotor**

◯ Interface Interface inherited from Regulated Motor

BaseMotor.java


public interface BaseMotor {

void forward();void backward();

void stop();
}

Finally

Thank you for reading. If you have any mistakes or points to improve, I would appreciate it if you could let me know.