I am learning the Exception handling in java (basically in inheritance)

前端 未结 4 961
刺人心
刺人心 2021-01-23 03:15

just look at program below..

import java.io.*;
import java.rmi.*;
class class1
{
  public void m1() throws RemoteException 
{
  System.out.println(\"m1 in class1         


        
4条回答
  •  逝去的感伤
    2021-01-23 03:36

    Like with return types (since Java 5) Exceptions mentioned inside the method signature are covariant.

    This means you can make them more specific in classes that inherit the original method. This concept is also called narrowing of constraints because you make it more specific what the types are.

    public class Foo {...}
    
    
    public class SomeException extends Exception {...}
    
    
    public class A{
        public Foo methodName() throws SomeException{...}
    }
    
    
    public class Bar extends Foo {...}
    
    
    public class SomeSpecificException extends SomeException {...}
    
    
    public class B extends A {
        public Bar methodName() throws SomeSpecificException {...}
    }
    

    So you can always go "down" the Inheritance hierarchy.

    // Doesn't compile    
    public class B extends A {
        public Object methodName() throws Exception {...}
    }
    

    Trying to widen the constraints doesn't work.

提交回复
热议问题