Home > database >  If a child class and parent class both implement the same interface, why is it only the parent class
If a child class and parent class both implement the same interface, why is it only the parent class

Time:05-09

I have three classes below AnimalActions an interface, and two other classes Animal which is the parent of Human

The AnimalActions interface is as follows:

public interface AnimalActions {

  public String greeting(); // how an animal says hello

  public String angryAction(); // how an animal says "im angry"

  public String happyAction(); // how an animal says "im happy"
}

When I have the class Animal implement AnimalActions I get a compiler error, forcing me to add the unimplemented methods, so the Class needs to look like this:

public class Animal implements AnimalActions {

  @Override
  public String greeting() {
    return "default greeting";
  }

  @Override
  public String angryAction() {
    return "default angry action";
  }

  @Override
  public String happyAction() {
    return "default happy";
  }

}

But when I then make a class Human that extends Animal and implements AnimalActions there is no compiler error forcing me to override the methods. This is perfectly acceptable to Eclipse.

public class Human extends Animal implements AnimalActions{

}

I can, however, add the unimplemented methods and change them from Animal, if I want to. I'm just not forced to do it.

The weird thing is that if I remove extends Animal from this class, then I am forced to add unimplemented methods. Why would I not be forced to add the unimplemented methods?

Every time I think I get a grasp on OOP I get confused about something weird like this. Is it total "nonsense" to have both a parent and child class implementing the same interface? Would it be better to just have extends Animal only?

Thanks a lot. I know this questions been asked here is the same question, but there was no code to go with the question or answer so it was a bit abstract for me.

CodePudding user response:

This is simply because the child gets access to all parent methods, as well as the overriden methods from the Interface. You can again override these methods, but then you need to call super.someMethod() if you need to call the parents implementation.

  • Related