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?
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With