JavaRush /Java Blog /Random EN /Mechanism of overriding methods or Override in Java

Mechanism of overriding methods or Override in Java

Published in the Random EN group
Hello! You already use methods in Java and know a lot about them. Surely you have come across a situation where in one class there were many methods with the same name, but different arguments. If you remember, in those cases we used the mechanism of method overloading. Let's take a look at a different situation today. Imagine that we have one common method, but it should do different things depending on which class it was called in. How to implement such behavior? To understand, let's take the parent class Animaldenoting animals, and create a method in it voice- " voice ":
public class Animal {

   public void voice() {

       System.out.println("Voice!");
   }
}
Although we have just started writing the program, the potential problem is most likely visible to you: there are a lot of animals in the world, and they all “speak” differently: cats meow, ducks quack, snakes hiss. How the method overriding mechanism works - 2 Our goal is simple: avoid creating a bunch of voting methods. Instead of creating methods voiceCat()for meowing, voiceSnake()for hissing, etc., we want voice()the snake to hiss, the cat to meow, and the dog to bark when the method is called. We can easily achieve this with the method override mechanism (Override in Java) . Wikipedia gives this explanation of the term "overriding" : Method overriding) in object-oriented programming, one of the features of a programming language that allows a subclass or child class to provide a specific implementation of a method already implemented in one of the superclasses or parent classes. It is, in general, correct. Overriding allows you to take some method of the parent class and write your own implementation of this method in each derived class. The new implementation will "replace" the parent in the child class. Let's see how it looks like with an example. Let's create 4 descendant classes for our class Animal:
public class Bear extends Animal {
   @Override
   public void voice() {
       System.out.println("Р-р-р!");
   }
}
public class Cat extends Animal {

   @Override
   public void voice() {
       System.out.println("Meow!");
   }
}

public class Dog extends Animal {

   @Override
   public void voice() {
       System.out.println("Woof!");
   }
}


public class Snake extends Animal {

   @Override
   public void voice() {
       System.out.println("Ш-ш-ш!");
   }
}
A little hack for the future: to override the methods of the parent class, go to the code of the derived class in Intellij IDE a, press Ctrl+O and select " Override methods... " from the menu. Get used to using hotkeys from the beginning, it speeds up writing programs! To set the behavior we want, we did a few things:
  1. We created a method in each descendant class with the same name as the method in the parent class.
  2. We told the compiler that we did not just call the method the same as in the parent class: we want to override its behavior. For this "message" to the compiler, we put an annotation @Override ("overridden") over the method.
    The @Override annotation above the method tells the compiler (and the programmers who read your code too): “It's OK, this is not a mistake and not my forgetfulness. I remember that there is already such a method, and I want to override it.

  3. We wrote the implementation we need for each descendant class. The snake should hiss when called voice(), the bear should growl, etc.
Let's see how it will work in the program:
public class Main {

   public static void main(String[] args) {

       Animal animal1 = new Dog();
       Animal animal2 = new Cat();
       Animal animal3 = new Bear();
       Animal animal4 = new Snake();

       animal1.voice();
       animal2.voice();
       animal3.voice();
       animal4.voice();
   }
}
Console output: Woof! Meow! Rrr! Sh-sh-sh! Great, everything works as it should! We have created 4 parent class reference variables Animaland assigned them to 4 different child class objects. As a result, each object behaves differently. For each of the derived classes, the overridden method voice()has replaced the "native" method voice()from the class Animal(which prints just "Voice!" to the console). How the method overriding mechanism works - 3 The override has a number of limitations:
  1. The overridden method must have the same arguments as the parent method.

    If a voiceparent class method accepts as input String, the overridden method in the child class must also accept as input String, otherwise the compiler will throw an error:

    public class Animal {
    
       public void voice(String s) {
    
           System.out.println("Voice! " + s);
       }
    }
    
    public class Cat extends Animal {
    
       @Override//error!
       public void voice() {
           System.out.println("Meow!");
       }
    }

  2. The overridden method must have the same return type as the parent method.

    Otherwise, we will get a compilation error:

    public class Animal {
    
       public void voice() {
    
           System.out.println("Voice!");
       }
    }
    
    
    public class Cat extends Animal {
    
       @Override
       public String voice() {         //error!
           System.out.println("Meow!");
           return "Meow!";
       }
    }

  3. The access modifier of the overridden method also cannot differ from the "original" one:

    public class Animal {
    
       public void voice() {
    
           System.out.println("Voice!");
       }
    }
    
    public class Cat extends Animal {
    
       @Override
       private void voice() {      //error!
           System.out.println("Meow!");
       }
    }
Method overriding in Java is one of the tools for implementing the idea of ​​polymorphism (the OOP principle we talked about in the last lecture). Therefore, the main advantage of using it will be the same flexibility that we talked about earlier. We can build a simple and logical system of classes, each of which will have specific behavior (dogs bark, cats meow), but a single interface - one method voice()for all instead of a bunch of methods voiceDog(), voiceCat()etc.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION