简体   繁体   中英

How to get the same instance of a class in Java?

Good morning,

I have one little problem. I created one class named Map(). In this class there in one method that generate an Array. Then i created other two classes (Top and Bottom) that extend Map. Then I created 2 objects. One of Top and one of Bottom. I want to get the same array for the Top's object and for the Bottom's object. Here is the code Source:

public class Map{
    public Map(){}

    public int [] yTopValues()
    {
        int [] arrayTopY = new int[100];
        for(int i=0;i<100;i++)
            arrayTopY[i]=randomInt(-50,50);//it puts in i-th position an int between 50 and -50
        return arrayTopY;
    }

    public int [] yBottomValues()
    {
        int [] arrayBottomY = yTopValues;
        for(int i=0;i<100;i++)
            arrayBottomY[i]=arrayBottomY[i]-250;
        return arrayBottomY;
    }

    public int [] xValues()
    {
        int [] arrayX = new int[100];
        for(int i=0;i<100;i++)
            arrayX[i]=randomInt(0,50);//it puts in i-th position an int between 0 and 50
        return arrayX;
    }
//other stuff
}


public class TopMap extends Map{

    public TopMap(){
        this.area=new Area(new Polygon(
            this.xValues,
            this.yTopValues,
            200)            
    );
    }

public class BottomMap extends Map{

    public BottomMap(){
        this.area=new Area(new Polygon(
            this.xValues,
            this.yBottomValues,
            200)            
    );
    }

In the View class I created two objects one of TopMap and one of BottomMap then I drew the areas with g2.draw(topMap.area) and g2.draw(bottomMap.area)

I need the 2 polygons to be similar, but both of them are different because the method is executed twice. What should I do? Thank you very much!!

The class Map does not hold the array. It is local only to the xValues() method. If you want the other classes to get that exact array do this:

/*
 * Since this is a variable in the CLASS field, this object will
 * be accessible to the child class.
 */
private int[] arrayX = new int[100];

public Map(){
     createArrayX(); // This makes sure that the array is created, or else
     // every value inside of it will be 0.
}

public void createArrayX(){ // Exact same thing as xValues(), but without the return type
     for(int i=0;i<100;i++){
        arrayX[i]=randomInt(0,50);
     }
}

public int[] getArrayX(){ // The method that gets the array.
     return arrayX;
}

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