Problem:
The exception that the method should throw is defined in the parent class or interface, so how to define the exception that will be thrown when the subclass overrides the method:
First define the exception and the parent class:
1 classException1extendsException {}2 classException2extendsException {}3 classException3extendsException {}4 classException1_1extendsException1 {}5 classException2_1extendsException2 {}6 classException3_1extendsException3 {}7 classSuperclass {8 Public voidMethod1 ()throwsException1, Exception2, Exception3 {}9}
The correct method overrides:
1. Subclass methods can only throw subsets of the parent class exception:
1 Public class extends Superclass {2 @Override3public void method1 () {} 4 }
public class Testexceptionlimit Span style= "color: #0000ff;" >extends superclass {@Override public
void method1 () Exception1 {}}
1 Public class extends Superclass {2 @Override3public void Throws Exception1, Exception2, Exception3 {}4 }
All three of the above can be.
2. Subclasses can throw the export class of the parent class exception:
1 Public class extends Superclass {2 @Override3public void Throws exception1_1, exception2_1 {}4 }
3. There is also a special case where a subclass inherits a parent class and implements an interface, and the parent class and interface define a signature-like method at the same time, but throws an exception differently, then the subclass should define its own method exception:
The new code:
1 classException4extendsException {}2 classException5extendsException {}3 4 classSuperclass {5 Public voidMethod1 ()throwsexception4{}6 }7 InterfaceTestInterface {8 Public voidMethod1 ()throwsException5;9}
Correct coverage:
1 Public class extends Implements testinterface {2 @Override3public void Method1 () {}4 }
Note: Do not throw any exceptions, as can be shown below:
1 Public class extends Implements testinterface {2 @Override3public void Throws Exception4 {}4 }
This code is encoded with an error message: Exception Exception4 is not compatible with throws clause in Testinterface.method1 (). Indicates that the exception that is defined by the interface does not match, and if you try to throw Exception5 it will tell you that the exception defined by the parent class does not match, so don't write yet--! , Java designers are still very user-friendly ~ ~ ~
Limitations of exception in method inheritance