[SOLVED] Interfaces like in Java?

Hi,

I am searching for something like an interface in java but i don't know how to do it.

I've tried this but with no success:

class Test1 {
  public:
    virtual void test1();
};

class Test2 : public Test1 {
  public:
    void test1() {
      Serial.begin(9600);
      Serial.println("test");
    }
};

void setup() {
  Test1 test = Test2();
  test.test1();
}

void loop() {

}

when i tried to compile i got this:

C:\Users\schnu\AppData\Local\Temp\cc7qsv4w.ltrans0.ltrans.o: In function `Test1::Test1(Test1&&)':

C:\Development\Arduino\Test/Test.ino:1: undefined reference to `vtable for Test1'

C:\Development\Arduino\Test/Test.ino:1: undefined reference to `vtable for Test1'

C:\Users\schnu\AppData\Local\Temp\cc7qsv4w.ltrans0.ltrans.o: In function `setup':

C:\Development\Arduino\Test/Test.ino:16: undefined reference to `Test1::test1()'

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino Pro or Pro Mini.

Is there any way to do it?

You have to create an instance of the class:

class Test1 {
  public:
    virtual void test1();
};

class Test2 : public Test1 {
  public:
    void test1() {
      Serial.begin(9600);
      Serial.println("test");
    }
};

Test2 instanceOfTest2;

void setup() {
  instanceOfTest2.test1();
}

void loop() {
}

But how can I call the method in class that extends Test1 without knowing the class?

You can call the virtual method of any derived class by using a pointer to the base class:

class Test1 {
  public:
    virtual void test1() = 0;  // Make this interface purely virtual
};

class Test2 : public Test1 {
  public:
    void test1() {
      Serial.begin(9600);
      Serial.println("test");
    }
};

Test2 instanceOfTest2;
Test1 *basePointer = &instanceOfTest2;

void setup() {
  basePointer->test1();
}

void loop() {
}

It works! Thanks!

I am new here, should i mark this post as something and if yes how?

You can change the title to included "[SOLVED]".

BTW, consider the example here: array of objects - #7 by gfvalvo - Programming Questions - Arduino Forum