BDubs
BDubs

Reputation: 53

Getting an error about an undefined method(constructor) when I'm looking right at it? (Java)

I'm getting an error here that says I haven't defined a method, but it is right in the code.

class SubClass<E> extends ExampleClass<E>{
      Comparator<? super E> c;
      E x0;

      SubClass (Comparator<? super E> b, E y){
           this.c = b;
           this.x0 = y;
      }

      ExampleClass<E> addMethod(E x){
           if(c.compare(x, x0) < 0)
               return new OtherSubClassExtendsExampleClass(c, x0, SubClass(c, x)); 
               //this is where I get the error                        ^^^^^^
      }

I did define that Constructor for SubClass, why is it saying that I didn't when I try to pass it in that return statement?

Upvotes: 2

Views: 269

Answers (3)

YoK
YoK

Reputation: 14505

As rightly pointed out by others there is missing new required to invoke constructor.

Whats happening in your case here is that due to missing new your call is treated as method call, And in your class there is not method SubClass(c, x). And Error undefined method is correct in your case as there is no method named SubClass(c, x)

You need to correct same :

return new OtherSubClassExtendsExampleClass(c, x0, new SubClass(c, x));

Upvotes: 1

jjnguy
jjnguy

Reputation: 138864

I think you want it to be:

                                       // new is needed to invoke a constructor 
return new OtherSubClassExtendsExampleClass(c, x0, new SubClass(c, x));

Upvotes: 2

Nikita Rybak
Nikita Rybak

Reputation: 68006

You probably want new SubClass(c, x) instead of SubClass(c, x). In java you invoke constructor in different way than method: with new keyword.

More on the subject.

Upvotes: 3

Related Questions