Inheritance , method signature , method overriding and throws clause

前端 未结 4 1152
半阙折子戏
半阙折子戏 2021-02-02 12:56

My Parent class is :

import java.io.IOException;
public class Parent {
        int x = 0;
        public int getX() throws IOException{
        if(x         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 13:22

    You have the freedom to override a method without the throws keyword, because if you want to develop a method by controlling all the exceptions, then you can do that by overriding the method without any throws clause.

    But remember one thing that if you want to include the throws clause in the subclass method, then the throws clause must associate with the exception which must be the same or the subclass of the exception what is thrown by its superclass method. for example-

    class Super{
        void a()throws IOException{
            ......
        }
    }
    class Sub extends Super{
        void a()throws IOException{
            ......
        }
    }
    

    The a() method of class Sub must throw IOException or any subclass of IOException, otherwise compiler will show error.

    That means if you write

    void a()throws Exception
    

    in the class Sub, then it will cause compilation error.

提交回复
热议问题