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();
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With