0

my code is like this: i have two classes first class:

public class Box<E> {

E data1;

    public Box(E data) {
        this.data1 = data;
    }
    public E getData() {
        return data1;
    }
}

second class:

public class IntBox extends Box<Integer>{

    Integer data;

    public IntBox(Integer data) {
        this.data = data;
    }

    public Integer getData() {
        return data;
    }
}

why doesn't this class extend from Box<E>?

1
  • You've specified that it extends Box<Integer>, so that is the class that it extends from. Commented Apr 1, 2012 at 14:03

3 Answers 3

1

That won't compile.

Your second class should be:

public class IntBox extends Box<Integer>{  
    public IntBox(Integer data) {
        super(data);
    }
}

And then it will properly extend it and use Box's methods.

Sign up to request clarification or add additional context in comments.

Comments

1

I wouldn't create a new class for this purpose since IntBox class doesn't add functionality to Box, but rather simply makes it more restrictive. Instead would simply declare Box to use Integer. i.e.,

public class Foo {
   public static void main(String[] args) {
      Box<Integer> intBox = new Box<Integer>(300);
      System.out.println("data is: " + intBox.getData());
   }
}

Comments

0

The later class extends from the first generic class. That should be no bigger issues with this example. Just make sure you call the constructor of the base class by super(data); in the IntBox constructor.

Comments

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.