Home>

Is it possible to put the instances r1, r2, r3 in an AAA type array and use the aaa method to find the area of ​​each of r1, r2, r3?

I would like to create a graphic array, shuffle it, and extract the information of the instance directly using the array.

I would appreciate it if anyone could tell me.
Thank you.

Corresponding source code
public class A {
    public static void main (String [] args) {
        AAA [] aaa = new AAA [3];
        aaa [0] = r1;
        aaa [1] = r2;
        aaa [2] = r3;
        System.out.println (aaa [0] .getClass (). getName ());

    }

        static RRR r1 = new RRR (10,10);
        static RRR r2 = new RRR (20,20);
        static RRR r3 = new RRR (30,40);

}
class AAA {

    AAA () {
        }
}
class RRR extends AAA {
    int height;
    int width;
    RRR (int height, int width) {
        getArea ();
    }
    int getArea () {
        return this.height * this.width;
    }
}
  • Answer # 1

    If you do not write the getArea method in the AAA class, you cannot call getArea in the RRR class.
    You also need a set of height and width in the RRR constructor.

    public class A {
        public static void main (String [] args) {
            AAA [] aaa = new AAA [3];
            aaa [0] = r1;
            aaa [1] = r2;
            aaa [2] = r3;
            for (int i = 0;i<3;i ++)
                System.out.println (aaa [i] .getClass (). getName () + ":" + aaa [i] .getArea ());
        }
        static RRR r1 = new RRR (10, 10);
        static RRR r2 = new RRR (20, 20);
        static RRR r3 = new RRR (30, 40);
    }
    class AAA {
        AAA () {}
        int getArea () {return 0;}
    }
    class RRR extends AAA {
        int height;
        int width;
        RRR (int height, int width) {
            this.height = height;
            this.width = width;
        }
        int getArea () {
            return this.height * this.width;// this. Does not have to be
        }
    }

Related articles