Marin
Marin

Reputation: 12920

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 " .

Any ideas? thanks

Upvotes: 9

Views: 30719

Answers (4)

reederz
reederz

Reputation: 971

Make String walk() implementations public. That will fix it

Upvotes: 1

Bozho
Bozho

Reputation: 597402

The error eclipse gives is:

Cannot reduce the visibility of the inherited method from Walk

The method must be public, because it is defined in an interface.

Upvotes: 2

Ted Hopp
Ted Hopp

Reputation: 234857

Interface methods must be public. You need to declare walk() as a public method in Cat.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

Methods in interfaces are implicitly public. However, methods in classes are package-visible by default. You cannot reduce the visibility of an overriden method, i.e. 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.

Upvotes: 20

Related Questions