-4

I have a constructor with variable initial_Age

public Person(int initial_Age) {
    if(initial_Age<0){
        age=0;
    }

I want to use initial_Age in other methods but it is giving error(variable not initialized)

public void amIOld() {
    if(this.initial_Age>0){
        age=this.initial_Age;
    }

What should I do ?

mpromonet
  • 11,326
  • 43
  • 62
  • 91
  • 1
    Use an [instance variable](http://stackoverflow.com/questions/16686488/java-what-is-an-instance-variable). – Mage Xy Jan 04 '16 at 16:43
  • Thats a `local variable` it can only be used locally where it was declared in a method/constructor. Use a `instance Variable` it can be accessed any constructor or method or any instance as long as it is `public` – John Pangilinan Jan 04 '16 at 16:47

2 Answers2

0

Try to do something like this:

private int initial_Age;

public Person(int initial_Age) {
 this.initial_Age =initial_Age;
  if(initial_Age<0){
    age=0;
 }

And you can use initial_Age everywhere in the Person class.

Abdelhak
  • 8,299
  • 4
  • 22
  • 36
0

To answer your question.

public class Person {
    private int age;

    public Person(int initialAge) {
        this.age = Math.max(initialAge, 0);
    }

    public boolean amIOld() {
        return this.age > 0;
    }
}

This way the age for one person is constant. U will need to change the logic.

Flowy
  • 420
  • 1
  • 5
  • 15