6. Abstract classes and interfaces
Review the presentation Abstract Classes and Interfaces
Tasks
- Create a Human class
- Create the Martian class
- Implement the methods of the Martian and Human classes
- More information
Create a Human class
Explore the package jtm.activity06 and create a Human class that implements the Humanoid interface:
- Right-click the package main.java.jtm.activity06 and select New — Class
- Type class name: Human
- Click Add.. and select Humanoid in the main.java.jtm.activity06 package.
- In the Which method stubs would you like to create? section, select Inherited abstract methods
- Click Finish
Create the Martian class
Create the Martian class that implements the Humanoid, Alien, and Cloneable interfaces:
- Right-click the main.java.jtm.activity06 package and select New — Class.
- Enter class name: Martian
- In the interfaces section, click Add.. and select:
- Humanoid from the main.java.jtm.activity06 package,
- Alien from the main.java.jtm.activity06 package,
- Cloneable from the java.lang package.
- In the Which method stubs would you like to create? section, select Inherited abstract methods
- Click Finish
Implement the methods of the Martian and Human classes
Implement the methods as required, as described in the interface definitions and unit test checks.
Notes:
- When Humanoid is hungry, it eats and gains weight. If Alien eats Humanoid, it kills it.
- When implementing Humanoid eat(), it must take an Integer, but Alien eat() must take an Object.
- When Humanoid vomits, it loses the weight of what it ate.
- Human vomit() only takes an Integer, but Alien can vomit any Object.
If clone() is called on Martian, its structure must be cloned recursively for the contents of all "stomachs". This can be done by implementing the internal method clone(Object), for example:
/*
* Implementation of Object clone() method for Cloneable interface
* @see https://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html
*/
@Override
public Object clone() throws CloneNotSupportedException {
return clone(this);
}
private Object clone(Object current) {
// TODO implement cloning of current object
// and its stomach
}Implement the toString() method for the Human and Martian classes in the following format:
@Override
public String toString() {
return "ClassName: " + weight + " [" + stomach + "]";
}where ClassName is Human for a human, and Martian for a Martian.
For example, if the current object is a Martian and it has another Martian in its "belly" and then a human with 3 in its belly, it should display:[Martian: 3 [Martian: 4 [Human: 5 [3]]]