方法重载与方法重写

1.方法重载(overload)

重载规则:

  1. 同一个类中;
  2. 方法名必须相同;
  3. 方法参数列表不同(参数个数,参数类型);
  4. 补充:方法的重载与与返回值类型无关
 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.");  
      }  
  }  

重写规则:

  1. 要求子类方法的返回值类型、方法名(参数列表)与父类方法一样
  2. 子类的方法修饰符不能小于父类
  3. 若父类方法抛异常,子类方法抛的异常类型不能大于父类
  4. 子父类的方法必须同为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();  
     }  
 }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值