简体   繁体   中英

How to create a constructor that takes the capacity of a class that contains an integer and an array of objects

Hello i defined the following Fish class with the following private attributes(basically its just a class that contains a string indicting the type of fish and an integer containing its size in centimeters. I also created get methods for each attribute,a constructor that takes the size and species of the fish and a toString() method that returns a string in the following format: A 10cm Pike ):

public class Fish 
{
  private int size;
  private String species;

public int getSize()
{
  return this.size;
}

public String getSpecies()
{
  return this.species;
}

public Fish(int s, String p)
{
  size = s;
  species = p;
}

public String toString()
{
  return("A " + this.size + " cm " + this.species);
  }
}

Then I defined a Pond class that defines the following private attributes:

fish - an array which will contain all Fish objects that are in the pond

numFish - an int indicating the # of fish that are currently in the pond

and this what I did: (if I am wrong please let me know)

public class Pond 
{
  private int numFish;
  private Fish [] fishes;

}

now what I am having trouble with in particular is creating a constructor that takes the capacity of the pond, where the capacity is the maximum number of fish that can be stored in the pond at any time. I am not really sure how to create an array as a parameter of a constructor. Also I am having trouble with creating a method called isFull() which returns a boolean indicating whether or not the pond has reached its capacity of fish. Any help is appreciated, thank you so much!

So, you want a constructor that takes a capacity as argument:

public Pond(int capacity)

And the capacity is thus the length of the array used to store the fishes:

public Pond(int capacity) {
    this.fishes = new Fish[capacity];
}

Arrays, like almost everything else, are covered in the Java tutorial. Googling for "Java tutorial arrays" finds it in an instant: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Now, when is the pond full? It seems to me that it's full if the number of fishes is equal to its capacity:

public boolean isFull() {
    return numFish == fishes.length;
}

You have to make the constructor like that or you can make the setter methods in your Pond class

public Pond(int capacity) {
    this.fishes = new Fish[capacity];
}

and you can create isFull method logic like

if (numFish == capacity)

{
  System.out.println("Pond is full");
}

Use a constructor similar to the following:

public Pond(int numberOfFish)
{
   numFish=numberOfFish;
   fishes=new Fish[numberOfFish];
}

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