简体   繁体   English

Java-访问私有实例变量

[英]Java - access private instance variables

I need to access the private variables from the following class listing (Species.java) in order to use them in the KlingonOx.java class. 我需要从以下类列表(Species.java)中访问私有变量,以便在KlingonOx.java类中使用它们。

The purpose of the KlingonOx.java class is to determine after how many years the population of the Elephant species will be larger than the population of the Klingon Ox species. KlingonOx.java类的目的是确定多少年后大象物种的数量将大于Klingon Ox物种的数量。

Here is the Species.java class: 这是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);
}
}

Here is the KlingonOx.java class: 这是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");
    }
}
}

The KlingonOx.java class gives me the error that "population" and "growthRate" are private instance variables in Species and therefore cannot be accessed. KlingonOx.java类给我的错误是“种群”和“ growthRate”是Species中的私有实例变量,因此无法访问。 I've tried to use the getPopulation and getGrowthRate method calls to retrieve the variables but I'm not sure how to do so correctly. 我尝试使用getPopulation和getGrowthRate方法调用来检索变量,但是我不确定如何正确执行操作。

Any feedback is appreciated. 任何反馈表示赞赏。

In class with variable: 在具有变量的类中:

class Foo {
  private int variable;

  public int getVariable() { return variable; }
}

in client class: 在客户类中:

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

That's pretty much everything. 那几乎就是一切。

Instead of using klingonox.population , you should use klingonox.getPopulation() - the same goes for your other Species objects as well. 而不是使用klingonox.population ,应该使用klingonox.getPopulation() -其他Species对象也是如此。

That should be the only change you need to make in order to use the getPopulation method. 这应该是您使用getPopulation方法需要进行的唯一更改。

First, 第一,

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

if you are setting up the population pass the value klingonox.setPopulation(20) and why are you trying to assign population to population. 如果要设置人口,请传递值klingonox.setPopulation(20)以及为什么要尝试将人口分配给人口。 There is no field population in KlingonOx. KlingonOx中没有现场人口。 Your population name and growthRate should be already assigned when you called readInput(); 当您调用readInput()时,应该已经分配了您的总体名称和growthRate;

Same goes with the elephant object. 大象对象也是如此。

采用

klingonox.getPopulation();

private access modifier allows us to hide a variable so that the class declaring it can only be accessed. private访问修饰符允许我们隐藏变量,以便声明该变量的类只能被访问。 You class - 你上课-

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

 public int getPopulation(){return population;}
 public double growthRate(){return growthRate;}
}

This concept is also called encapsulation where we use public methods to access and modify private variables. 这个概念也称为封装,其中我们使用public方法来访问和修改private变量。

- You want to access the instance variable of the Super -Class from the Sub -Class. -您要访问的instance variable中的Super从-Class Sub级轿车。

- Use the super keyword, with the Getter-Setter methods. -通过Getter-Setter方法使用super关键字。

Eg: 例如:

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();

       ........
       ........
    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM