Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using inheritance, why is goPee() not defined in my test class?

I'm trying to use inheritance so that I can perform the code contained within the test class correctly. I'm unsure how to implement an abstract class or interface called Bathroom featuring the goPee() method. Do you know how to code it?

If I add either an abstract class or an interface and add them to the Human class via extends or implements respectively, I am always asked to write implementation in the Human class for goPee() method, which i don't want to do, as my goPee() method implementation is written in the Male and Female child classes.

import java.util.ArrayList;

class Human
{
  private String name;
  public Human (String name)
  {
    this.name = name;
  }
  public String getName()
  {
    return name;
  }
  public void eat()
  {
    System.out.println(name + " went to fridge.");
  }
}

class Male extends Human
{
  public Male(String name)
  {
    super(name);
  }
  public void goPee()
  {
    System.out.println(getName() + " stood up.");
  }
}

class Female extends Human
{
  public Female(String name)
  {
    super(name);
  }
  public void goPee()
  {
    System.out.println(getName() + " sat down.");
  }
}

public class TestHuman
{
  public static void main(String[] args)
  {
    ArrayList<Human> arr = new ArrayList<Human>();
    arr.add(new Male("john"));
    arr.add(new Female("sally"));
    for (int count = 0; count < arr.size(); count++)
    {
      arr.get(count).eat();
      arr.get(count).goPee();
    }
  }
}
like image 714
Danny Rancher Avatar asked Dec 17 '22 01:12

Danny Rancher


1 Answers

You must define a goPee() method in the Human class. Since you're overriding it in both subclasses, it can be an abstract method. This also means that Human must be abstract.

abstract class Human
{
  private String name;
  public Human (String name)
  {
    this.name = name;
  }
  public String getName()
  {
    return name;
      }
  public void eat()
  {
    System.out.println(name + " went to fridge.");
  }
  public abstract void goPee();
}

Declaring an abstract method in Human ensures that all subclasses of Human implement the goPee() method with the same parameters and return type. This allows you to call goPee() on a Human without knowing whether it is a Male or Female, since you know both implement it.

like image 159
MALfunction84 Avatar answered Jan 19 '23 01:01

MALfunction84