6. Abstract classes and Interfaces
Main steps
- Create Human class
- Create Martian class
- Implement methods of Martian and Human classes
- Optional information
Create Human class
Create Human class which implements Humanoid interface:
- Right-click on package main.java.jtm.activity06 and select New — Class
- Enter class name: Human
- Press Add.. in interfaces section and select Humanoid in main.java.jtm.activity06 package
- For section Which method stubs would you like to create? select Inherited abstract methods
- Press Finish
Create Martian class
Create Martian class, which implements Humanoid, Alien and Cloneable interfaces:
- Right-click on package main.java.jtm.activity06 and select New — Class
- Enter class name: Martian
- Press Add.. in interfaces section and select:
- Humanoid from main.java.jtm.activity06 package,
- Alien from main.java.jtm.activity06 package,
- Cloneable from java.lang package.
- For section Which method stubs would you like to create? select Inherited abstract methods
- Press Finish
Implement methods of Martian and Human classes
Implement methods according to the required logic, which is described in interface definitions and expected results from unit tests.
Notes:
- When Humanoid is hungry, it eats and gains weight. If Alien eats Humanoid it kills it.
- Implementation of Humanoid eat() should accept Integer, but implementation of Alien eat() should accept Object.
- When Humanoid vomits, it loses weight of eaten item.
- Human vomit() only Integer, but Alien vomit any Object.
When clone() is called for Martian, its structure should be cloned recursively for content of all stomaches. You can do it by implementing internal method clone(Object) like this:
/*
* 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 toString() method for Human and Martian classes in following format:
@Override
public String toString() {
return "ClassName: " + weight + " [" + stomach + "]";
}where ClassName is Human for human and Martian for martian.
For example, if current object is martian and its stomach contains another martian and then human with 3 in its stomach, it should show:[Martian: 3 [Martian: 4 [Human: 5 [3]]]