【问题标题】:Java - access private instance variablesJava - 访问私有实例变量
【发布时间】:2012-12-10 02:46:14
【问题描述】:

我需要从以下类列表 (Species.java) 中访问私有变量,以便在 KlingonOx.java 类中使用它们。

KlingonOx.java 类的目的是确定在多少年后大象种群将大于克林贡牛种群。

这里是 Species.java 类:

import java.util.Scanner;

public class Species
{
private String name;
private int population;
private double growthRate;

public void readInput()
{
    Scanner keyboard = new Scanner(System.in);
    System.out.println("What is the species' name?");
    name = keyboard.nextLine();

    System.out.println("What is the population of the species?");
    population = keyboard.nextInt();

    while(population < 0)
    {
        System.out.println("Population cannot be negative.");
        System.out.println("Reenter population:");
        population = keyboard.nextInt();
    }

    System.out.println("Enter growth rate (% increase per year):");
    growthRate = keyboard.nextDouble();
}

public void writeOutput()
{
    System.out.println("Name = " + name);
    System.out.println("Population = " + population);
    System.out.println("Growth rate = " + growthRate + "%");
}

public int predictPopulation(int years)
{
    int result = 0;
    double populationAmount = population;
    int count = years;

    while( (count>0) && (populationAmount>0) )
    {
        populationAmount = (populationAmount + (growthRate/100) * populationAmount);
        count --;
    }

    if (populationAmount > 0)
        result = (int)populationAmount;
    return result;
}

public Species(String name)
{
    name = name;
    population = 0;
    growthRate = 0.0;
}

public Species(int population)
{
    name = "";
    if (population > 0)
        population = population;
    else
    {
        System.out.println("ERROR: using a negative" + "population.");
        System.exit(0);
    }
    growthRate = 0.0;
}

public Species(double growthRate)
{
    name = "";
    population = 0;
    growthRate = growthRate;
}

public Species(String name, int population, double growthRate)
{
    name = name;
    if (population > 0)
        population = population;
    else
    {
        System.out.println("ERROR: using a negative" + "population.");
        System.exit(0);
    }
    growthRate = growthRate;
}

public Species()
{
    name = "";
    population = 0;
    growthRate = 0;
}

public void setSpecies(String newName, int newPopulation, double newGrowthRate)
{
    name = newName;
    if (newPopulation >= 0)
        population = newPopulation;
    else
    {
        System.out.println("ERROR: using a negative " + "population.");
        System.exit(0);
    }

    growthRate = newGrowthRate;
}

public void setName(String name)
{
    name = name;
}

public void setPopulation(int population)
{
    if (population > 0)
        population = population;
    else
    {
        System.out.println("ERROR: using a negative" + "population."); 
        System.exit(0);
    }
}

public void setGrowthRate(double growthRate)
{
    growthRate = growthRate;
}

public String getName()
{
    return name;
}

public int getPopulation()
{
    return population;
}

public double getGrowthRate()
{
    return growthRate;
}

public boolean equals(Species otherObject)
{
    return (name.equalsIgnoreCase(otherObject.name)) &&
           (population == otherObject.population) &&
           (growthRate == otherObject.growthRate);
}
}

这是 KlingonOx.java 类:

import java.util.Scanner;
public class KlingonOx extends Species
{
public static void main(String[] args) 
{
    new KlingonOx().run();
}

public void run()
{     
    Species klingonox = new Species();
    Species elephant = new Species();

    System.out.println("Please enter data on the species Klingon Ox."); 
    klingonox.readInput();
    klingonox.writeOutput();
    klingonox.setPopulation(int population);
    population = population;
    klingonox.setGrowthRate(double growthRate);
    growthRate = growthRate;

    System.out.println("Please enter data on the species Elephant.");
    elephant.readInput(); 
    elephant.writeOutput();
    elephant.setPopulation(population);
    population = population;
    elephant.setGrowthRate(growthRate);
    growthRate = growthRate;

    int year = 0;
    if(klingonox.population < elephant.population)
    {
        while(klingonox.population < elephant.population)
        {
            klingonox.population = (int)(klingonox.population + (klingonox.population * (klingonox.growthRate/100) ) );
            elephant.population=(int)(elephant.population + (elephant.population * (elephant.growthRate/100) ) );
            year++;
        }

        System.out.println("KLINGON OX EXCEEDS ELEPHANT IN" + year + "YEARS");
    }

    else
    {
        while(klingonox.population > elephant.population)
        {
            klingonox.population=(int)(klingonox.population+(klingonox.population*(klingonox.growthRate/100)));
            elephant.population=(int)(elephant.population+(elephant.population*(elephant.growthRate/100)));
            year++;
        }
    System.out.println("ELEPHANT EXCEEDS KLINGON OX IN" + year + "YEARS");
    }
}
}

KlingonOx.java 类给我的错误是“population”和“growthRate”是 Species 中的私有实例变量,因此无法访问。我尝试使用 getPopulation 和 getGrowthRate 方法调用来检索变量,但我不确定如何正确执行此操作。

感谢任何反馈。

【问题讨论】:

  • 使用Species#getPopulationSpecies#getGrowthRate 方法,这就是它们的存在...

标签: java instance-variables private-members


【解决方案1】:

在有变量的类中:

class Foo {
  private int variable;

  public int getVariable() { return variable; }
}

在客户端类中:

class Bar {
   void method() {
     ...
     Foo foo = new Foo();
     int population = foo.getVariable();
     ...
   }
}

差不多就是这样。

【讨论】:

    【解决方案2】:

    您应该使用klingonox.getPopulation(),而不是使用klingonox.population - 您的其他Species 对象也是如此。

    这应该是您使用 getPopulation 方法所需进行的唯一更改。

    【讨论】:

      【解决方案3】:

      首先,

      klingonox.setPopulation(int population);
      population = population;
      klingonox.setGrowthRate(double growthRate);
      growthRate = growthRate;
      

      如果您要设置人口,请传递值 klingonox.setPopulation(20) 以及为什么要尝试将人口分配给人口。克林贡牛没有田间种群。当您调用 readInput(); 时,您的人口名称和growthRate 应该已经分配;

      大象对象也是如此。

      【讨论】:

        【解决方案4】:

        使用

        klingonox.getPopulation();
        

        【讨论】:

          【解决方案5】:

          private 访问修饰符允许我们隐藏一个变量,以便声明它的类只能被访问。你上课-

          public class Species {
           private String name;
           private int population;
           private double growthRate;
          
           public int getPopulation(){return population;}
           public double growthRate(){return growthRate;}
          }
          

          这个概念也称为封装,我们使用public 方法来访问和修改private 变量。

          【讨论】:

            【解决方案6】:

            - 你想从Sub-Class 访问Super-Class 的instance variable

            - 使用 super 关键字和 Getter-Setter 方法。

            例如:

            public class Species
            {
            private String name;
            private int population;
            private double growthRate;
            
            public int getPopulation(){
            
            return this.population;
            
            }
            
            public double getGrowthRate(){
            
            return this.growthRate;
            
            }
            
            public String getName(){
            
            return this.name;
            
            }
            
            // Setters...........
            
            }
            
            
            public class KlingonOx extens Spices{
            
            .......
            .......
            
              public static void main(String[] args){
            
            
                   int p = super.getPopulation();
            
                   ........
                   ........
                }
            
            
            }
            

            【讨论】:

              猜你喜欢
              • 2012-05-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-10-23
              • 2013-04-22
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多