Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"override" super class member in subclass java

Kind of a noob question, this, but I cannot figure it out.

This is animal.java. I want it to be a superclass for all animal subclasses. It's in the same package as all the subclasses.

public class Animal {
    protected static String call = "Animals make noises, but do not have a default noise, so we're just printing this instead.";
        public static void sound()
        {
            System.out.println(call);
        }
}

This is cow.java

class Cow extends Animal {
    call = "moo";
}

Evidently, this does not run. But I want to be able to run Cow.sound() and have the output read "moo". I also want to be able to create more classes that override the 'call' with their own string. What should I be doing instead?

like image 562
Skeleton Avatar asked Oct 22 '15 11:10

Skeleton


1 Answers

You can't override instance variables. You can only override methods. You can override the sound method (once you change it to an instance method, since static methods can't be overridden), or you can override a method that sound will call (for example getSound()). Then each animal can returns its own sound :

public class Animal {
    static String call = "Animals make noises, but do not have a default noise, so we're just printing this instead.";
    public void sound()
    {
        System.out.println(getSound ());
    }

    public String getSound ()
    {
        return call;
    }
}

class Cow extends Animal {
    @Override
    public String getSound ()
    {
        return "moo";
    }
}
like image 136
Eran Avatar answered Oct 03 '22 06:10

Eran