Search code examples
javainheritancemethods

Is it possible to extend Methods in Java?


I know it is possible to do this in Java:

public class animal {...}

And then

public class dog extends animal {...}

Then you can write whatever dog methods that can access animal method.

However, I am wondering is there a way to extend methods

for example

public void generateAnimal() {...}

and then

public void generateDog() extends generateAnimal() {...}

But this is not passing the compiler. So my question is:

Is it possible to inherit methods in Java?


Solution

  • Yes.

    public class Animal {
       public void someAction() {
          System.out.println("from Animal class");
       }
    }
    
    public class Dog extends Animal {
       public void someAction() {
          super.someAction();
          System.out.println("from Dog class");
       }
    }
    
    public class Main {
    
      public static void main(String[] args){
          Animal dog = new Dog();
          dog.someAction();
      }
    }
    

    Output:

    from Animal class    
    from Dog class
    

    So you extend functionality of method, but better to use composition instead of inheritance.