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

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

table of contents

  1. What is an interface?
  2. Code structure 1-0. Sample code to implement the process in the interface 1-1. Sample code that creates a class and implements an interface
  3. Sample code for 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 ** method specifications only **. The methods are listed in the interface, but their ** processing ** is not written.

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


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


Point: ** Class that implements the interface ** Define the processing content of the method Actually process


[Reference article] Implemented interface! How to use implements in Java


1. Code structure

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

First, let's take a look at the code below. 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{
	
	//Instance generation
	//RegulatedMotor:interface
	//EV3LargeRegulatedMotor:Class that implements the interface
	private static RegulatedMotor l_a = new EV3LargeRegulatedMotor(MotorPort.A);
	
	public static void main(String[] args) {
		
		//Instance generation
		//Customize the methods in the interface RegulatedMotorListener to define the process
		final RegulatedMotorListener listener = new RegulatedMotorListener() {
			
			//Customize the following two methods of the interface RegulatedMotorListener
			
			//Customize the method that is called when the motor starts spinning
			@Override
			public void rotationStarted(
					final RegulatedMotor motor,
					final int tachoCount,
					final boolean stalled,
					final long timeStamp) {
				//What to customize
				System.out.println("Started");
				Delay.msDelay(500);
			}
			//Customize the method that is called when the motor stops spinning
			@Override
			public void rotationStopped(
					final RegulatedMotor motor,
					final int tachoCount,
					final boolean stalled,
					final long timeStamp) {
				//What to customize
				System.out.println("Stopped");
				Delay.msDelay(500);

			}
				
		};
		
		//The addListener method takes an instance of RegulatedMotorListener as an argument
		//If there is any movement in the motor, it will be notified 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);
		
	}
}

Sample code overview

  1. I want to use the ** addlistener method ** to display characters at the start and end of motor rotation **. ※void addListener(RegulatedMotorListener listener) Add a listener object that will notify you when rotation starts or stops

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

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

  4. However, since the interface ** does not define the processing of the method **, even if an instance is created, ** the processing cannot actually be performed **. Therefore, ** customize the method in the interface to define the process ** so that the process can be performed.


Organize sample code

◯ Interface: ** Regulated Motor ** Implementation class: EV3LargeRegulatedMotor

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

◯ Method: ** rotationStarted () ** Only specifications are defined in RegulatedMotorListener Method called when the motor starts rotating

◯ Method: ** rotationStopped () ** Only specifications are defined in RegulatedMotorListener Method called at the end of motor rotation

◯ Method: ** addlistener () ** void addListener(RegulatedMotorListener listener) It takes an object ** generated from the interface ** as an argument. Specifications are 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 called RotateStateEvent by yourself to implement the interface RegulatedMotorListener. In it, customize the method in RegulatedMotorListener to define the process.

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) {
        //Take 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 RegulatedMotor 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 RegulatedMotor 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 for interface TimerListnener and implementation class Timer

◯ Create your own SecondCounter class to handle the Timer class. The Timer class takes an instance of the TimerListener interface (the class that implements it) as an argument. Then, ** call the ** timedOut method (= processing) in the TimerListener interface (the class that implements it) ** every specified cycle **.

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

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 {
        //TimedOut every 1000ms()The method is called by the Timer
        //Customize and define the processing contents of the methods in the interface
        @Override
        public void timedOut() {
            //Add one by one
            second++;
            System.out.print(second);
            //Make a sound every 5 seconds
            if(second % 5 == 0 ) {
            	Sound.beep();
            }
        }
    }
}
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 {
	
    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();

        //Repeat processing 20 times
        for (int i = 0; i < 20; i++) {
        	
            if(i == 10) {
            	//Reset timer
            	System.out.print("reset ");
            	counter.reset();
            }else if(i > 15) {
            	//Slow driving
            	System.out.print("slowdown ");
            	l_a.setSpeed(100);
            }else {
            	//To accelerate
            	//count*Set speed to 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) It takes an instance of the period and TimerListener class (the class that implements it) as arguments.

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

3. Relationship between motor class and interface in leJOS

Let's look at the relationship between the motor class and the interface.

・ ** Class BaseRegulatedMotor ** ・ ** Class EV3 Large Regulated Motor ** ・ ** Interface Regulated Motor ** ・ ** Interface BaseMotor **

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


** Class BaseRegulatedMotor **

◯ The following interface is implemented BaseMotor,RegulatedMotor...

◯ Subclass EV3LargeRegulatedMotor, EV3MediumRegulatedMotor...

BaseRegulatedMotor.java


//Excerpt from the 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 use extends to inherit a class.

[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 Large Regulated Motor **

◯ The following interface is implemented Interface: BaseMotor, Encoder, RegulatedMotor, Tachometer

EV3LargeRegulatedMotor.java


//EV3LargeRegulatedMotor class that inherits from 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 Regulated Motor **

◯ Implemented in the following classes BaseRegulatedMotor, EV3LargeRegulatedMotor, EV3MediumRegulatedMotor...

◯ Inherits the interface BaseMotor

//Excerpt from the interface Regulated Motor
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. I would appreciate it if you could let me know if there are any mistakes or points that need to be improved.

Recommended Posts

[ev3 × Java] Interface, implementation and inheritance (event handling)
Inheritance and interface.
Java and Swift comparison (3) Class implementation / Class inheritance / Class design
Advanced inheritance abstract, interface -java
JAVA learning history interface inheritance
Achieve Mixin-like implementation inheritance: Ruby module, Java interface, PHP trait
[Java] Method call error when inheritance and interface implementation are performed at the same time
[Java beginner] About abstraction and interface
Java 15 implementation and VS Code preferences
[JAVA] Difference between abstract and interface
BloomFilter description and implementation sample (JAVA)
java (interface)
[Java] Inheritance
Java implementation to create and solve mazes
Java inheritance
[Java] Inheritance and structure of HttpServlet class
[java] interface
Java inheritance
[Java / Swift] Comparison of Java Interface and Swift Protocol
java (inheritance)
[Java] Contents of Collection interface and List interface
Java Basic Learning Content 6 (Inheritance / Abstract Class / Interface)
PostgreSQL Pub / Sub functionality and Java client implementation
Questions in java exception handling throw and try-catch
Java exception handling?
About Java interface
[Java] Class inheritance
interface and abstract
[Java] About interface
Java and JavaScript
XXE and Java
[Java] Exception handling
[Java] Functional interface
About java inheritance
About interface, java interface
☾ Java / Exception handling
Java exception handling
Java exception handling
[JAVA] What is the difference between interface and abstract? ?? ??
Use of Abstract Class and Interface properly in Java
[Java Silver] (Exception handling) About try-catch-finally and try-with-resource statements
About synchronized and Reentrant Lock (Java & Kotlin implementation example)
[Java] Handling of character strings (String class and StringBuilder class)