packagetong.yue.day4_264;importjava.io.FileNotFoundException;importjava.io.IOException;importjavax.swing.JButton;importjavax.swing.JComponent;/*** 子类重写(覆盖)父类的方法必须满足的条件:
* 1.父类中的方法在子类中必须可见,即子类继承了父类中的该方法(可以显式的使用super关键字来访问父类中的被重写的方法),
* 如果父类中的方法为private类型的,那么子类则无法继承,也无法覆盖。
* 2.子类和父类的方法必须是实例方法,如果父类是static方法而子类是实例方法,或者相反都会报错。
* 如果父类和子类都是static方法,那么子类隐藏父类的方法,而不是重写父类方法。
* 3.子类和父类的方法必须要具有相同的函数名称、参数列表,并且子类的返回值与父类相同或者是父类返回类型的子类型(jdk1.5之后)。
* 如果方法名称相同而参数列表不同(返回类型可以相同也可以不同),那么只是方法的重载,而非重写。
* 如果方法名称和参数列表相同,返回值类型不同,子类返回值类型也不是父类返回值类型的子类,编译器就会报错。
* 4.子类方法的访问权限不能小于父类方法的访问权限(可以具有相同的访问权限或者子类的访问权限大于父类)
* 访问权限由高到低:public、protected、包访问权限、private。如果子类方法的访问权限低于父类,则编译器会给出错误信息
* 5.子类方法不能比父类方法抛出更多的编译时异常(不是运行时异常),即子类方法抛出的编译时异常或者和父类相同或者是父类异常的子类。
*@authortong
**/
public classInheritance {/***@paramargs*/
public static voidmain(String[] args) {//TODO Auto-generated method stub
}
}classPareant {public voiddoSomething() {
}public static voiddoSomething1() {
}publicJComponent doSomething2() {return null;
}publicJComponent doSomething3() {return null;
}public void doSomething4(intx) {
}public void doSomething5() throwsFileNotFoundException{
}private void doSomething6(intx) {
}
}class Sub extendsPareant {//父类中该方法是私有的,对子类不可见,所以子类无法继承和覆盖父类的私有方法//在这里并没有覆盖父类的私有方法,而是在子类中创建了一个新的和父类同名的方法而已,这两个方法没有任何关系
private void doSomething6(intx) {
}//报错,父类为实例方法,子类为静态方法//This static method cannot hide the instance method from Pareant
public static voiddoSomething() {
}//报错,父类为静态方法,子类为实例方法//This static method cannot hide the instance method from Pareant
public voiddoSomething1() {
}//正确,父类的返回值为JComponent,是子类返回值类的父类,从jdk1.5开始,重写父类方法时的返回值可以与父类相同,也可以是父类的子类
publicJButton doSomething2() {return null;
}//报错,父类的返回值为JComponent,子类返回值类型为int,子类返回值与父类返回值类型不同,也不是父类返回值的子类//The return type is incompatible with Pareant.doSomething3()
public intdoSomething3() {return 1;
}//报错,父类的访问权限为public,子类为protected,子类的访问权限不能低于父类,可以高于或者等于父类的访问权限//Cannot reduce the visibility of the inherited method from Pareant
protected void doSomething4(intx) {
}//报错,子类不能抛出比父类更多的异常,父类抛出FileNotFoundException异常,子类抛出的IOException是父类异常的父类//子类只能抛出和父类一样的异常,或者是父类异常的子类,而不能超过父类//Exception IOException is not compatible with throws clause in Pareant.doSomething5()
public void doSomething5() throwsIOException{
}
}