Inheritance , method signature , method overriding and throws clause

前端 未结 4 1137
半阙折子戏
半阙折子戏 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:15

    Easy to remember

    1. Access modifier can be changed from restricted to less restricted,
      for example from protected to public, but not vise versa
    2. throws signature can be changes from parent exception to child exception class, but not vise versa

    This code is valid

    public class A  {
    
        protected String foo() throws Exception{
            return "a";
        }
    
        class B extends A {
            @Override
            public String foo() throws IOException{
                return "b";
            }
        }
    }
    

    Overrided foo method has public access, not protected and throws IOException that child of Exception

    This code is not valid

    public class A  {
    
        public String foo() throws IOException{
            return "a";
        }
    
        class B extends A {
            @Override
            protected String foo() throws Exception{
                return "b";
            }
        }
    }
    

    Overrided foo method has more restricted access modifier and throws Exception that NOT child of IOException

    By the way you can override method from superclass and not throw ecxeptions at all

    This code valid

    public class A  {
    
        public String foo() throws IOException{
            return "a";
        }
    
        class B extends A {
            @Override
            public String foo(){
                return "b";
            }
        }
    }
    

提交回复
热议问题