0

I have created a child class InheritanceTest which extends parent class Parent. Parent class is an abstract class and InheritanceTest class overrides the abstract method abstractMethod(). When I write, Parent P = new InheritanceTest();, it is working fine. But when I write, List<Number> num = new ArrayList<Integer>();, it is giving me compilation error saying that "Type mismatch: cannot convert from ArrayList<Integer> to ArrayList<Number>"

Note: Number is an abstract class which is extended by Integer class in jdk.

Please find below my code:

import java.util.ArrayList;
import java.util.List;


abstract class Parent {
    public void test() {
      System.out.println("parent version of test called");
    }

    public abstract void abstractMehod();
}

public class InheritanceTest extends Parent{

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
         ArrayList<Number> num = new ArrayList<Integer>();

        Parent parent = new InheritanceTest();

    }

    public void test() {
        System.out.println("child version of test called");
    }

    @Override
    public void abstractMehod() {
        // TODO Auto-generated method stub

    }

}

Please explain me the reason behind this behavior.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Rushi Shah
  • 2,031
  • 2
  • 14
  • 10
  • How is it possible? If possible then will it be meaningful? Super class don't know about anything its sub-class. Make sure to avoid creating a cyclic dependencies. – Braj May 31 '14 at 11:39
  • In super class just keep the reference of itself instead of sub-class reference that make more sense. – Braj May 31 '14 at 11:42
  • Before you decide to post your question make sure that it contains correct examples. You need to understand that `` is treated as HTML tag (strange one but tag) so it will not be printed. To print it you need to either post it as code or change `<` to `<`. – Pshemo May 31 '14 at 11:45

0 Answers0