Search code examples
javasubclassgetter-settersuperclass

Java: using setter of a subclass when creating an object of type Superclass


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!


Solution

  • Cast p1 to Man:

    ((Man) p1).setAge(13);