hibc
hibc

Reputation: 277

java: passing argument to copy constructor

Inside of class ATester
{
   private A<Integer> p1,p2;

    p1 = new B<Integer>();
    p2 = new B<Integer>( p1);

}

public class B<E extends Comparable<? super E>> implements A<E>
{
     public B()   // default constructor
     {
        // skip
     }

     public B(B other)  // copy constructor
     {
        // skip
     }

}

I want to define a copy constructor, which takes another B as argument but when I pass p1 into

p2 = new B<Integer>( p1);

when compile, it gives me error message

"no suitable constructor found for B< A < Integer > >"

What should I change or add?

Upvotes: 0

Views: 231

Answers (3)

HRgiger
HRgiger

Reputation: 2790

Your B already implements A, So change constructor arg from B to A:

public class B<E extends Comparable<? super E>> implements A<E>
{
     public B()   // default constructor
     {
        // skip
     }

     public B(A other)  // copy constructor
     {
        // skip
     }



}

Then you can use both A and B as a valid cons parameter;

    A<Integer> p1, p2;
    B<Integer> c = new B<Integer>();

    p1 = new B<Integer>(c);
    p2 = new B<Integer>( p1);

Upvotes: 0

Yogendra Singh
Yogendra Singh

Reputation: 34367

You need to cast your p1 to B<Integer> before calling the copy constructor.

    p2 = new B<Integer>( (B<Integer>)p1);

Or you can define another constructor accepting the Interface type e.g.

    public B(A<E> other)  // copy constructor
    {
         //type cast here and use it
    }

Upvotes: 2

Jatin
Jatin

Reputation: 31724

Change it to

Or call as p2 = new B<Integer>( (B<Integer>)p1);

Because what you are trying to do is send A<Integer> to B in the constructor. Ultimately it is

B b = element of type A<Integer>

Which is wrong due to contra-variance of argument type. Either change the argument type in you B constructor as per design or do the above mentioned

Upvotes: 1

Related Questions