"override" superclass member in java subclass

Kind of a noob question, this, but I can't figure it out.

This is an animal. Java. I want him to be a superclass for all animal subclasses. It is in the same package as all 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"; } 

Obviously this does not work. But I want to be able to run Cow.sound () and output the output of "moo". I also want to be able to create more classes that override the "call" with their own string. What should I do instead?

+5
source share
2 answers

You cannot override instance variables. You can override methods. You can override the sound method (as soon as you change it to an instance method, since static methods cannot be overridden), or you can override the method that sound will call (for example, getSound() ). Then each animal can return 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"; } } 
+6
source

Variables are never overestimated, so a subclass variable that replaces a superclass variable will not be possible. Another option is to override the method, but its static, static also cannot be overridden.

Thus, with the current setup, this is not possible if you do not want to override non-static methods.

0
source

Source: https://habr.com/ru/post/1234261/


All Articles