티스토리 뷰

You can use polymorphism to solve that problem.
First define the base class/abstract class/interface with the method generateItem(), derive specified classes and override/implement generateItem() method.
Here is implementation with interface:

interface Base{
    void generateItem();
    }
    class Derived1 implements Base{
        @Override
            public void generateItem() {
                    System.out.println("generateItem() from Derived1");
                        }
                        }
                        class Derived2 implements Base{
                            @Override
                                public void generateItem() {
                                        System.out.println("generateItem() from Derived2");
                                            }
                                            }
                                            class Main {
                                                public static void main(String[] args) {
                                                        List<Base> list = new ArrayList<>();
                                                                list.add(new Derived1());
                                                                        list.add(new Derived2());
                                                                                list.forEach(Base::generateItem);
                                                                                    }
                                                                                    }
                                                                                    

The output is:

generateItem() from Derived1
generateItem() from Derived2

For more, you can read about polymorphism here.

-------------------

The idiomatic approach is to define an abstract generateItem() on Enchant. If you can't modify Enchant for some reason, you could create an abstract subclass of Enchant, and make all your subclasses inherit from that.

You could also try making an interface with generateItem() that all the subclasses implement and store the Interface type in the ArrayList.

If you still can't do any of those for whatever reason, you should rethink your design. But as a last resort, you can use reflection to dynamically access the generateItem of each individual subclass. Just call .getClass() and then lookup the method and invoke it.

-------------------

Enchant서브 클래스가 구현해야하는 추상 메서드를 제공 합니다. 추상적으로 만드는 것은 Enchant메서드의 정의가 필요하지 않지만 하위 클래스는 필요하다는 것을 의미 합니다.

public class Enchant {
    public abstract Item generateItem();
    }
    

이 메서드는 static코드에 있는 메서드가 아니어야 합니다. 의 인스턴스에서 호출하기 때문에 인스턴스 메서드 여야합니다 Enchant.

-------------------

인터페이스 또는 추상 클래스로 인챈트를 만들고 파생 클래스에서 확장



출처
https://stackoverflow.com/questions/39940126
댓글
공지사항
Total
Today
Yesterday
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30