简体   繁体   English

子类java中的“覆盖”超类成员

[英]“override” super class member in subclass java

Kind of a noob question, this, but I cannot figure it out. 这是一个菜鸟问题,但我无法弄明白。

This is animal.java. 这是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 这是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". 但是我希望能够运行Cow.sound()并将输出读作“moo”。 I also want to be able to create more classes that override the 'call' with their own string. 我还希望能够使用自己的字符串创建更多覆盖'call'的类。 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() ). 您可以覆盖sound方法(一旦将其更改为实例方法,因为无法覆盖静态方法),或者您可以覆盖sound将调用的方法(例如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";
    }
}

Variables are never overriden, so sub class variable replacing supercall variable will not be possible. 永远不会覆盖变量,因此无法替换supercall变量的子类变量。 Another option was to override the method but then its static, static also cannot be overridden. 另一种选择是覆盖方法,但其静态,静态也不能被覆盖。

So with current setup its not possible unless you look to override non static methods. 因此,除非您希望覆盖非静态方法,否则使用当前设置是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM