+ Reply to Thread
Results 1 to 2 of 2

Thread: Storing subclass as superclass

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    24

    Storing subclass as superclass

    I have classes SubClass1 and SubClass2 that extend SuperClass. I need to store all of the objects extending SuperClass in a list . and then i`d like to retrieve the subclasses .

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    41
    here is what you need :
    Code:
    List<SuperClass> list = new ArrayList<SuperClass>();
        int count = 40;
        Random random = new Random();
        while(count-- > 0) {
            if(random.nextBoolean()) {
                list.add(new SubClass1());
            } else {
                list.add(new SubClass2());
            }
        }
        for (SuperClass superClass : list ) {
            if (superClass.getType().equals("SubClass1")){
                SubClass1 subClass = (SubClass1) superClass;
                System.out.println(subClass);
            }else if (superClass.getType().equals("SubClass2")){
                SubClass2 subClass = (SubClass2) superClass;
                System.out.println(subClass);
            }
        }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts