1.方法重载(overload)
重载规则:
- 同一个类中;
- 方法名必须相同;
- 方法参数列表不同(参数个数,参数类型);
- 补充:方法的重载与与返回值类型无关
public class OverloadDemo {
void test(){ //test()方法第一次重载,没有参数
System.out.println("No parameters");
}
void test(int a){ //test()方法第二次重载,一个整型参数
System.out.println("a: "+a);
}
void test(int a,int b){ //test()方法第三次重载,两个整型参数
System.out.println("a and b: "+a+" "+b);
}
double test(double a){ //test()方法第四次重载,一个双精度型参数
System.out.println("double a: "+a);
return a*a; //返回a*a的值
}
}
2.方法重写(override)
前提:有子类继承父类
子类继承父类后,若父类的方法对子类不适用,那么子类可以对父类的方法重写
class Animal {
public void eat(){
System.out.println ("Animal is eating.");
}
}
class Dog extends Animal{
public void eat(){
System.out.println ("Dog is eating.");
}
}
重写规则:
- 要求子类方法的返回值类型、方法名(参数列表)与父类方法一样
- 子类的方法修饰符不能小于父类
- 若父类方法抛异常,子类方法抛的异常类型不能大于父类
- 子父类的方法必须同为static或同为非static
import java.io.*;
public class Test {
public static void main (String[] args) {
Animal d = new Dog();
try {
d.eat();
}
catch (Exception e) {
}
}
}
class Animal {
public void eat() throws Exception{
System.out.println ("Animal is eating.");
throw new Exception();
}
}
class Dog extends Animal{
public void eat() throws IOException{
System.out.println ("Dog is eating.");
throw new IOException();
}
}