Java - access private instance variables

删除回忆录丶 提交于 2019-11-29 08:57:46

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.

That should be the only change you need to make in order to use the getPopulation method.

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. There is no field population in KlingonOx. Your population name and growthRate should be already assigned when you called readInput();

Same goes with the elephant object.

Use

klingonox.getPopulation();

private access modifier allows us to hide a variable so that the class declaring it can only be accessed. 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.

- You want to access the instance variable of the Super-Class from the Sub-Class.

- Use the super keyword, with the Getter-Setter methods.

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

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


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!