在Java中重写方法

在Java中重写方法,java,overriding,Java,Overriding,好的,我只是在学习java,并使用这个:教程。我现在在第37页,我似乎无法超越这条鱼。我很确定我完全复制了代码,但显然我做错了什么,所以这里是我的代码。 以下是宠物类: public class Pet { int age; float weight; float height; String color; public void sleep() { System.out.println( "Good ni

好的,我只是在学习java,并使用这个:教程。我现在在第37页,我似乎无法超越这条鱼。我很确定我完全复制了代码,但显然我做错了什么,所以这里是我的代码。 以下是宠物类:

public class Pet {
    int age;
    float weight;
    float height;
    String color;

    public void sleep() {
        System.out.println(
                "Good night, see you tommorow");
        }

    public void eat() {
        System.out.println(
        "I'm so hungry...let me have a snack like nachos!");
    }

    public String say(String aWord) {
        String petResponse = "OK!! OK!! " +aWord;
            return petResponse;
    }
}
这是鱼类中的超级种类:

public class Fish extends Pet {

    public String say(String something) {
        return "Don't you know that fish do not talk?"; 
    }

    int currentDepth=0;

    public void sleep() {
        System.out.println("I need to rest");
    }

    public int dive(int howDeep) {
        currentDepth=currentDepth + howDeep;
        System.out.println("Diving for " + howDeep + " feet");
        System.out.println("I'm at " + currentDepth + " feet below sea level");
        return currentDepth;
    }
}
FishMaster使用Fish类:

public class FishMaster {

    public static void main(String[] args) {

        Fish myLittleFish = new Fish();
        myLittleFish.say("Hello!");
        myLittleFish.dive(2);
        myLittleFish.dive(3);

        myLittleFish.sleep();
    }
}

问题是当我试图在Fish类中超越say方法时。虽然过度使用睡眠法效果很好,但say法不再起任何作用。我运行它,它不会像书上说的那样打印“难道你不知道鱼不会说话吗?”。是我做错了什么,还是say函数只是假设不打印任何内容。感谢您的反馈。

该方法返回字符串,但不打印。尝试:

System.out.println(myLittleFish.say("Hello!"));
澄清:

// we assign the string returned from the method to a variable
String sentence = myLittleFish.say("Hello!"); 
// we print the variable to screen
System.out.println(sentence);

该方法返回一个字符串,但不打印它。尝试:

System.out.println(myLittleFish.say("Hello!"));
澄清:

// we assign the string returned from the method to a variable
String sentence = myLittleFish.say("Hello!"); 
// we print the variable to screen
System.out.println(sentence);
您的
say()
方法所做的就是返回一个字符串。调用函数(
FishMaster.main()
)不处理此字符串。我想您希望打印出来时使用:

System.out.println(myLittleFish.say("Hello!"));
您的
say()
方法所做的就是返回一个字符串。调用函数(
FishMaster.main()
)不处理此字符串。我想您希望打印出来时使用:

System.out.println(myLittleFish.say("Hello!"));

你忘了把它打印到系统输出。返回的值没有打印。

您忘记将其打印到系统输出。返回的值只是没有打印出来。

我不知道,我不知道你接受了什么教程。Soory,我想在“this”上包含一个链接,但它在这里:查看教程,你可以看到,首先,他将
say()
方法的结果分配给一个字符串,然后他打印它。我会修改一下我的答案,这样会更清楚。好的,谢谢。另外,String是一个命令,还是仅仅是他选择编写的东西?String是一个类,而不是命令。继续读这本书,它会变得更清晰。我不知道,我不知道你学的是什么教程。Soory,我想在“this”上添加一个链接,但它就在这里:看看教程,你可以看到,首先,他将
say()
方法的结果赋给一个字符串,然后打印出来。我会修改一下我的答案,这样会更清楚。好的,谢谢。另外,String是一个命令,还是仅仅是他选择编写的东西?String是一个类,而不是命令。继续读这本书,它会变得更清晰。