Jack Davis
Jack Davis

Reputation: 605

Overriding a Method in Java

Ok, so I'm just learning java, and using this: http://www.myflex.org/books/JavaKid8x11.pdf tutorial. I'm currently on page 37, and I can't seem to over ride the fish. I'm pretty sure I copied the code exactly, but obviously I'm doing something wrong, so here is my code. Here is the class Pet:

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;
    }
}

That is the Super Class of the class of Fish:

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;
    }
}

The Fish class is used by FishMaster:

public class FishMaster {

    public static void main(String[] args) {

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

        myLittleFish.sleep();
    }
}

The problem is when I'm trying to over ride the say method in the Fish class. While over riding the sleep method worked fine, the say method doesn't do anything anymore. I run it, and it doesn't print "Don't you know fish can't talk?" as the book says it should. Am I doing something wrong, or is the say function just suppose to not print anything. Feedback is appreciated, thanks.

Upvotes: 0

Views: 255

Answers (3)

MByD
MByD

Reputation: 137272

The method returns a String, it doesn't print it. Try:

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

To clarify:

// 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);

Upvotes: 3

cyber-monk
cyber-monk

Reputation: 5560

You forgot to print it to system out. The value is being returned just not printed.

Upvotes: 0

dty
dty

Reputation: 18998

All your say() method does is return a String. The calling function (FishMaster.main()) doesn't do anything with this String. I expect you wanted to print it out with:

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

Upvotes: 1

Related Questions