0
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?

2
  • Change public B(B other) to public B(B<E> other). Commented Nov 24, 2012 at 21:16
  • @MarkoTopolnik.. It won't help. His reference type of p1, is A<Integer> Commented Nov 24, 2012 at 21:17

3 Answers 3

2

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
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

THank you very much! WOuld you please explain little more about (B<Integer>)p1? what does it mean?
Ok for example: Animal a = new Dog() is valid. because Dog is also an animal. What you are trying to do is: Dog a = new Animal(). Now dog cant be all animals. Hence it is wrong
A super type can be used instead of subtype, but not other way around. Above hence, I am type casting p1 from type A to type B<Integer>
And if I were you, I would change constructor of B to :public B(B<E> other) to avoid compile time warning
0

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);

1 Comment

This actually depends on design. I personally wouldn;t do it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.