You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 from Object, so this array can hold instances of Human, Dog, and Cat seamlessly.
  • The instanceof operator 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:15:18