从主方法访问子方法

  • 本文关键字:子方法 访问 方法 java
  • 更新时间 :
  • 英文 :


假设我有一个名为Farm的类

public class Farm extends java.lang.Object implements java.lang.Comparable<Farm>{

Farm由农场上的一组动物组成。我想看看农场里有多少头猪。

我们有

public class Pig extends Animal{
public double getPigCount(){
return pigCount;
}

我怎样才能在我的农场类中得到我的猪数?

public class Farm extends java.lang.Object implements java.lang.Comparable<Farm>{
public String HowMany(){
String newString += "There are " _____ + " pigs on the farm" + "n"; 
String newString +=" There are "____ + " cows on the farm"......etc
return newString;
}

我想访问主方法中的子方法,但我不确定如何准确地做到这一点。

您可以在Animal类中创建一个静态映射,该映射将动物的类型存储为键,并将创建的动物数量存储为值。

无论何时创建任何动物的实例,都要从每个动物的构造函数中增加其在map中的计数。

public abstract class Animal {
static HashMap<String, Integer> babies = new HashMap<>();
public static String howMany() {
StringBuilder sb = new StringBuilder("");
for (Entry<String, Integer> e : babies.entrySet()) {
sb.append("There are " + e.getValue() + " " + e.getKey() + " on the farm.n");
}
return sb.toString();
}
}

下面是三种动物的类,它们的构造函数在babies

中增加它们的计数
class Pig extends Animal {
public static final String ID = "Pigs";
public Pig() {
Animal.babies.put(ID, babies.containsKey(ID) ? babies.get(ID) + 1 : 1);
}
}
class Dog extends Animal {
public static final String ID = "Dogs";
public Dog() {
Animal.babies.put(ID, babies.containsKey(ID) ? babies.get(ID) + 1 : 1);
}
}
class Cow extends Animal {
public static final String ID = "Cows";
public Cow() {
Animal.babies.put(ID, babies.containsKey(ID) ? babies.get(ID) + 1 : 1);
}
}

最后我用一些数字测试代码

public static void main(String[] args) {
// Going to create 3 dogs, 4 pigs, and 5 cows
int d = 3, p = 4, c = 5;
while (d-- > 0) {
Dog tempD = new Dog();
}
while (p-- > 0) {
Pig tempP = new Pig();
}
while (c-- > 0) {
Cow tempC = new Cow();
}
System.out.println(Animal.howMany());
}

结果如下:

There are 4 Pigs on the farm.
There are 3 Dogs on the farm.
There are 5 Cows on the farm.

在Farm类中声明Pig, Cow成员变量。和所有类扩展java.lang.Object。所以你不需要扩展Object。

最新更新