简体   繁体   中英

How I can create any of these subclasses inside class M

I have superclass (Class A) with a number of subclasses (Class B, Class C, Class D). I would like to create objects of any of these subclasses inside another class (class M) so that I can add the objects to an arraylist inside the class M.

I would like to know how I can create any of these subclasses inside class M.

The best way to go is the use the factory design pattern.

Update #1

Check these links

I don't know if you are looking for a construction pattern or for a way to instantiate an inner class. If your problem is related to how to instantiate inner classes here is an hint:

public class A {
    public static class B {}
    public class C {}
}

class M {{
    A.B b = new A.B();

    A a = new A();
    A.C c =  a.new C();
}}

So for static inner classes, you can create instance with a regular 'new',
but for non static inner classes, you must create a first instance of the surrounding class, then call new for inner class on this instance:

    A a = new A();
    A.C c =  a.new C();
public A createObject(int i) {
  A result = null;
  switch(i) {
    case 1: 
      result = new B();
      break;

    case 2:
      result = new C();
      break;
  }
  return A;
}

You always create objects inside other objects. There is no other way of doing things in Java. Factory is the best approach. If you wish to keep things simpler you can just do it like this:

ArrayList<A> l = new ArrayList<A>();

l.add(new B());
l.add(new C());

since B and C are subclasses of class A.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM