简体   繁体   English

Java抽象类实现接口

[英]Java abstract class implements interface

I have the following interface and abstract class that implements it: 我有以下接口和实现它的抽象类:

interface Walk {
    String walk();
}

public abstract class Animal implements Walk {
    abstract String MakeNoise();
}

And the following concrete implementations: 以下具体实现:

class Cat extends Animal {
    String MakeNoise() {
        return "Meow";
    }

    @Override
    String walk() {
        return "cat is walking";
    }
}

class Dog extends Animal {
    @Override
    String walk() {
        return "Dog is walking";
    }

    @Override
    String MakeNoise() {
        return "bark";
    }
}

class Human {
    public void Speak() {
        System.out.println("...Speaking...");
    }
}

Putting it all together: 把它们放在一起:

class MainClass {
    public static void main(String[] args) {
        Random randomGen = new Random();

        Animal[] zoo = new Animal[4];
        zoo[0] = new Cat();
        zoo[1] = new Dog();
        zoo[2] = new Cat();
        zoo[3] = new Cat();
        // System.out.println(zoo[ randomGen.nextInt(2)].MakeNoise());
        for (Animal animal : zoo) {
            if (animal instanceof Dog) {
                Dog jeffrey = (Dog) animal;
                System.out.println(jeffrey.MakeNoise());
            }

        }
    }
}

I get this error 我收到这个错误

"walk() in Cat cannot implement walk() in Walk " . “cat中的walk()无法在Walk中实现walk()”。

Any ideas? 有任何想法吗? thanks 谢谢

Methods in interfaces are implicitly public . 接口中的方法是隐式public However, methods in classes are package-visible by default. 但是,默认情况下,类中的方法是包可见的。 You cannot reduce the visibility of an overriden method, ie you can't do stuff like this: 你无法降低重写方法的可见性,即你不能做这样的事情:

class A {
    public foo() {}
}

class B extends A {
    private foo() {}  // No!
}

class C extends A {
    foo() {}          // No! foo is package-visible, which is lower than public
}

In your case, the solution is to declare walk() as public in Dog and Cat . 在您的情况下,解决方案是在DogCat中将walk()声明为public

The error eclipse gives is: eclipse给出的错误是:

Cannot reduce the visibility of the inherited method from Walk 无法从Walk减少继承方法的可见性

The method must be public, because it is defined in an interface. 该方法必须是公共的,因为它是在接口中定义的。

Interface methods must be public. 接口方法必须是公共的。 You need to declare walk() as a public method in Cat. 您需要将walk()声明为Cat中的公共方法。

Make String walk() implementations public . 使String walk()实现public That will fix it 这将解决它

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

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