如何在for循环中从基类调用两个派生类的两个构造函数?

问题描述 投票:0回答:1

从我的基类中,我尝试从两个派生类each调用两个类构造函数。

我有两个派生类;我将它们称为 ClassA 和 ClassB。 ClassA 和 ClassB 都有两个自己的派生类。我将它们称为 ClassA1、ClassA2、ClassB1 和 ClassB2。这 4 个类都有一个构造函数,但它们的长度不同。

这个想法是使用数组和 for 循环来调用每个构造函数。这是我到目前为止所拥有的:

public class Base {

    int year;
    String brand;
    String name;
    
    Base(){
        year = 0;
        brand = "Default";
        name = "Default";
    }
    
    Base(int year, String brand, String name){
        this.year = year;
        this.brand = brand;
        this.name = name;
    }
    void display(){
        System.out.println("Year: " + year + "\nBrand: " + brand
        + "\nName: " + name);
    }
    
    public static void main(String[] args) {
          
        Base obj[] = new Base[4];
        obj[0] = new Base(); //I'm not sure what to do here
        obj[1] = new Base();
        obj[2] = new Base();
        obj[3] = new Base();
        
        for (int i=0; i < obj.length; i++) {
            obj[i] = new Base();
        }
    }
}

public class ClassA extends Base {
    int playerCount;
    boolean hasMods;
    double fileSize;

    
    ClassA(){
        playerCount = 0;
        hasMods = false;
        fileSize = 0;
    }
    
    ClassA(int year, String brand, String name, int playerCount,
            boolean hasMods, double fileSize){
        super(year, brand, name);
        this.playerCount = playerCount;
        this.hasMods = hasMods;
        this.fileSize = fileSize;
    }
    
    void display(){
        super.display();
        System.out.println("Max Number of Players: " + playerCount
        + "\nModding Capability?: " + hasMods
        + "\nStorage: " + fileSize + " gb");
    }
}

class ClassA1 extends ClassA{
    ClassA1(){
        super(2015, "Bethesda", "Fallout 4", 1, true, 30.0);
    }
}

class ClassA2 extends ClassA{
    ClassA2(){
        super(2007, "Bungie", "Halo 3", 4, false, 6.3);
    }
}

即使有了这个数组,它对我来说也没有多大意义。如果数组来自 Base,我认为它不会调用低于它的任何内容。如果数组是ClassA,它仍然无法获取特定的类。如果是ClassA1,那么其他所有的类都不能被调用。而且数组显然也不能是字符串。

我想象它是这样工作的:Array[x] value = new Arrayx;。问题是,我不确定这是否有效,或者如何做到这一点。

如果我能看到它如何与两个类中的一个一起工作,我相信我可以弄清楚另一个类的工作原理。

java arrays for-loop inheritance constructor
1个回答
0
投票

您似乎想创建一个对象数组,其中每个元素都是层次结构中不同类的实例。为此,您可以将数组声明为基类类型,然后实例化派生类的对象。

这是一个基于您提供的课程的示例:

class Base {
// Your existing code...
public static void main(String[] args) {
    // Create an array of the base class
    Base[] objArray = new Base[4];

    // Instantiate objects of the derived classes
    objArray[0] = new ClassA();
    objArray[1] = new ClassA1();
    objArray[2] = new ClassA2();
    objArray[3] = new ClassB1(); // Assuming ClassB1 is another derived class

    // Loop through the array and call display for each object
    for (Base obj : objArray) {
        obj.display();
        System.out.println(); // Add a line break between objects
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.