有没有办法在 base class 中使用重写函数? (在Java)

Is there a way to use overridden function in base class? (In Java)


我试图在使用子函数的基 class 中实现一个函数(在基 class 中定义为抽象函数)。我认为一个例子将以最好的方式说明问题。

abstract class Animal{
   public void doSomthing(){
      this.sound();
   }

   protected abstract void sound();
}

class Dog extends Animal{
   @Override
   protected void sound(){ 
   System.out.println("WAF"); 
 }
}

现在,当我尝试在 运行 时间内获取元素(通过看起来像 Animal factory method("Dog); 的工厂方法)并调用 doSomthing 方法时我得到了异常,因为它转到了抽象方法,我的问题是是否有任何方法可以绕过这个或这个问题的另一个解决方案。

 class myMain
{
   public static void main(String[]args)
   {
    Animal doggo = new Dog(); // create object for dog
    doggo.animalSound(); // call the sound for dog

   }
}
    class Animal 
{
  public void animalSound() 
  {
    System.out.println("The animal makes a sound");
  }
}
class Dog extends Animal
{
   public void animalSound()
   {
     System.out.println("The Dog Says bow wow! "); 
   }
}

我认为您在问题描述中提到的方法没有任何问题。也许你正在犯其他错误。检查以下工作代码:

abstract class Animal {
    public void doSomthing() {
        sound();
    }

    protected abstract void sound();
}

class Dog extends Animal {
    @Override
    protected void sound() {
        System.out.println("WAF");
    }
}

class AnimalFactory {
    static Animal animal;

    public static Animal factoryMethod(String animalName) {
        if ("Dog".equals(animalName)) {
            animal = new Dog();
        }
        return animal;
    }
}

class Main {
    public static void main(String[] args) {
        Animal animal = AnimalFactory.factoryMethod("Dog");
        animal.sound();
    }
}

输出:

WAF

super class 对 child class 方法的调用可以完成。 请参考下面 link 中提到的代码片段: Can a Parent call Child Class methods?