Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 391
Marin Avatar asked Dec 14 '11 22:12

Marin


2 Answers

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.

like image 101
Oliver Charlesworth Avatar answered Oct 03 '22 10:10

Oliver Charlesworth


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.

like image 23
Bozho Avatar answered Oct 03 '22 10:10

Bozho