java重载

1、定义

  在一个类中,有多个构造函数,只是名字一样,但参数不一样,返回值类型可相同也可不相同,这就叫做“重载(orderload)”;

  【只能重载构造函数】,重载只能出现一个类中或者一个子类中;

 1 package com.test.three;
 2 
 3 public class TestOrderLoad {
 4     public int test(){
 5         System.out.println("testInt");
 6         return 1;
 7     }
 8     public void test(int a){
 9         System.out.println("testVoid");
10     }
11     public String test(String str ,int a){
12         System.out.println("testStringInt");
13         return "testThree";
14     }
15     public String test(int a,String str){
16         System.out.println("testIntString");
17         return "testFour";
18     }
19     public static void main(String[] args) {
20         TestOrderLoad TOL = new TestOrderLoad();
21         System.out.println(TOL.test());
22         TOL.test(12);
23         System.out.println(TOL.test("SDF", 3));
24         System.out.println(TOL.test(234, "str"));
25     }
26 }

返回值结果:

testInt
1
testVoid
testStringInt
testThree
testIntString
testFour

2、重载与重写的区别:

  重载:参数列表必须不同,返回值类型可以相同也可不同(在同一个类中或者一个子类中)

  重写:参数列表必须相同,返回值必须相同,在子类中重写父类方法(父类声明,子类创建时,执行此类中的方法,只能是执行两者(子类父类)共有的方法);

原文地址:https://www.cnblogs.com/FanSunny/p/5534034.html