Home > Java > javaTutorial > body text

In Java, under what circumstances is method rewriting required?

PHPz
Release: 2023-04-21 11:58:08
forward
1708 people have browsed it

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();
       }
   }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template