Home  >  Article  >  Java  >  In Java, under what circumstances is method rewriting required?

In Java, under what circumstances is method rewriting required?

PHPz
PHPzforward
2023-04-21 11:58:081704browse

Occurrence conditions

1. The method names are the same

2. The parameter lists of the methods are the same (return type and data type)

3. The return value of the method is the same

4. The overridden method cannot throw a new exception or a wider checked exception than the checked exception declared by the overridden method.

But it is possible to throw fewer, more limited or no exceptions.

Example

  import java.io.*;
   public class Test {
       public static void main (String[] args) {
           Animal h = new Horse();
           try {
               h.eat();   
           }
           catch (Exception e) {
           }
       }
   }
 
   class Animal {
       public void eat() throws Exception{
           System.out.println ("Animal is eating.");
           throw new Exception();
       }
   }
   
   class Horse extends Animal{
       public void eat() throws IOException{
           System.out.println ("Horse is eating.");
           throw new IOException();
       }
   }

The above is the detailed content of In Java, under what circumstances is method rewriting required?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete