Java实现printSleep静态方法:处理多类型对象数组输出
Solution for the printSleep() Static Method
Alright, let's put together a solid implementation that fits your requirements. First, let's start with basic class definitions for Human, Dog, and Cat—they don't need any extra methods for this task, just the core declarations:
// Basic class definitions (required for the method to work) class Human {} class Dog {} class Cat {}
Now here's the full printSleep() static method, wrapped in a utility class for completeness. We'll iterate through the input array, use Java's instanceof operator to check each object's type, and print the corresponding sleep duration:
public class SleepDurationPrinter { public static void printSleep(Object[] creatures) { // Iterate over every element in the input array for (Object creature : creatures) { if (creature instanceof Human) { System.out.println("Humans sleep 8 hours"); } else if (creature instanceof Dog) { System.out.println("Dogs sleep 14 hours"); } else if (creature instanceof Cat) { System.out.println("Cats sleep 16 hours"); } // Optional: Uncomment below to handle unexpected types // else { // System.out.println("Unknown creature's sleep duration"); // } } } // Example usage to test the method public static void main(String[] args) { Object[] testCreatures = {new Human(), new Dog(), new Cat(), new Human()}; printSleep(testCreatures); } }
Key Details to Note:
- We use
Object[]as the parameter type because all Java classes inherit fromObject, so this array can hold instances ofHuman,Dog, andCatseamlessly. - The
instanceofoperator is ideal here—it checks if an object is an instance of a specific class (or its subclass), which is exactly what we need for type-based printing. - The enhanced for-loop (
for (Object creature : creatures)) makes array iteration clean and easy to read, avoiding manual index management. - The optional else block lets you handle unexpected object types in the array, which is a good practice for robustness.
If you run the main method, the output will be:
Humans sleep 8 hours Dogs sleep 14 hours Cats sleep 16 hours Humans sleep 8 hours
内容的提问来源于stack exchange,提问作者AA123
相关产品推荐
相关产品推荐

