歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java方法的重載以及構造函數的理解

Java方法的重載以及構造函數的理解

日期:2017/3/1 10:11:56   编辑:Linux編程

一直對重載和構造函數的概念不是很理解,看了mars的視頻以後有一種豁然開朗的感覺,寫下來跟大家一起分享下。

方法的重載有3個條件:

1、函數位於同一個類下面;

2、方法名必須一樣;

3、方法的參數列表不一樣。

比如有以下的例子:

  1. class Student {
  2. void action(){
  3. System.out.println("該函數沒有參數!");
  4. }
  5. void action(int i)
  6. {
  7. System.out.println("有一個整形的參數!");
  8. }
  9. void action(double j)
  10. {
  11. System.out.println("有一個浮點型的參數!");
  12. }
  13. }
該類中定義了3個方法,但是3個方法的參數列表不一樣;

下面在主函數中調用這個類:

  1. public class Test {
  2. /**
  3. * @param args
  4. * @author weasleyqi
  5. */
  6. public static void main(String[] args) {
  7. // TODO Auto-generated method stub
  8. Student st = new Student();
  9. st.action();
  10. st.action(1);
  11. st.action(1.0);
  12. }
  13. }
看看運行結果:

從控制台的輸出可以看出,我在主函數中實例化一個student對象,分別調用了這個對象的3中方法,由於3個方法的參數不一樣,所以可以看到輸出的結果也不一樣;

構造函數的使用:

定義一個Sutdent類,類裡面定義兩個屬性:

  1. class Student {
  2. String name;
  3. int age;
  4. }
此時的Student類中沒有構造函數,系統會自動添加一個無參的構造函數,這個構造函數的名稱必須和類的名稱完全一樣,大小寫也必須相同,系統編譯完了之後是以下的情況:
  1. class Student {
  2. Student()
  3. {
  4. }
  5. String name;
  6. int age;
  7. }

主函數中實例化兩個對象:

  1. public class Test {
  2. /**
  3. * @param args
  4. * @author weasleyqi
  5. */
  6. public static void main(String[] args) {
  7. // TODO Auto-generated method stub
  8. Student st = new Student();
  9. st.name = "張三";
  10. st.age = 10;
  11. Student st2 = new Student();
  12. st2.name = "李四";
  13. st2.age = 20;
  14. }
  15. }
從主函數可以看出,此時的Student對象的屬性比較少,創建的實例也比較少,如果屬性多再創建多個實例的話,這個代碼的量就很大,這時候,我們可以添加一個帶參數的構造函數,如下:
  1. class Student {
  2. Student(String n, int a)
  3. {
  4. name = n;
  5. age = a;
  6. }
  7. String name;
  8. int age;
  9. }
主函數的代碼如下:
  1. public class Test {
  2. /**
  3. * @param args
  4. * @author weasleyqi
  5. */
  6. public static void main(String[] args) {
  7. // TODO Auto-generated method stub
  8. Student st = new Student("張三",10);
  9. Student st2 = new Student("李四",20);
  10. System.out.println("st的name:" + st.name +", st的age:" + st.age);
  11. System.out.println("st2的name:" + st2.name +", st的age:" + st2.age);
  12. }
  13. }
此時系統運行的結果如圖:

從運行結果可以看出,我們在實例化Student對象的時候,調用了帶參數的構造函數,節省了很多的代碼,要注意:如果我們在Student類中定義了一個帶參數的構造函數,但是沒有寫無參的構造函數,這個時候我們在主函數中就不能定義 Student st = new Student();如果在Student類中加上無參的構造函數就可以實現這樣的實例化。

Copyright © Linux教程網 All Rights Reserved