0

I have a superclass Person and two subclasses Man and Woman

in subclass Man, I have an instance variable age:

public class Man extends Person{

   private double age;

   public final static double MIN_AGE = 0.0;
   public final static double MAX_AGE = 65.0;

  //no argument constructor
  public Man(){
    super();
    initAge();  // This randomly selects age
  }

   /* Setters and getters */
   public void setAge (double ageIn) 
   {
      /* Assign a value only if it is within the allowed range */
      if (ageIn>= MIN_AGE && ageIn<= MAX_AGE )
      {
        this.age = ageIn;
      }
      else if (ageIn< MIN_AGE)
      {
        this.age = MIN_AGE;
      }
      else if (ageIn > MAX_AGE)
      {
        this.age = MAX_AGE;
      }
   }

  public double getAge()
  {
    return age;
  }
} 

Now, my task is to create a Man object and test whether the setter works and whether initAge works by showing the value of "age: with getAge.

I also have to initialize the object using the following:

Person p1 = new Man();

However, if initialized this way, I do not have access to Man's setters and getters. Is there a way around this other than doing:

Man p1 = new Man();

Thanks!

3 Answers 3

1

Cast p1 to Man:

((Man) p1).setAge(13);
Sign up to request clarification or add additional context in comments.

Comments

1

You can add abstract methods to the Person class:

public abstract class Person {

    public abstract double getAge();
    public abstract setAge(double ageIn);
}

Or, if the methods are sex-independent, move them to the parent, so Man and Woman can inherit.

2 Comments

Thank you. A good idea but I must not change the superclass. Thanks for the help, anyways!
In this case, if you are SURE the reference is a Man object, the only thing you can do is to use a cast. if (p1 instanceof Man) ((Man) p1).setAge(42);
1

You're going to have to use Person p1 = new Man(); because that's the only way if you really do not want to create a Man object of an instantiated new Man().

Now in order to access the setters and getters as a Person, you would need to mask that by casting the Man type over it.

((Man) p1).setAge(double)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.