Java方法的重载以及构造函数的理解


一直对重载和构造函数的概念不是很理解,看了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.     /** 
  4.      * @param args 
  5.      * @author weasleyqi 
  6.      */  
  7.     public static void main(String[] args) {  
  8.         // TODO Auto-generated method stub   
  9.             Student st = new Student();  
  10.             st.action();  
  11.             st.action(1);  
  12.             st.action(1.0);  
  13.     }  
  14.   
  15. }  
看看运行结果:

从控制台的输出可以看出,我在主函数中实例化一个student对象,分别调用了这个对象的3中方法,由于3个方法的参数不一样,所以可以看到输出的结果也不一样;

构造函数的使用:

定义一个Sutdent类,类里面定义两个属性:

  1. class Student {  
  2.   
  3.     String name;  
  4.     int age;  
  5. }  
此时的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.               
  12.             Student st2 = new Student();  
  13.             st2.name = "李四";  
  14.             st2.age = 20;  
  15.     }  
  16. }  
从主函数可以看出,此时的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.     /** 
  4.      * @param args 
  5.      * @author weasleyqi 
  6.      */  
  7.     public static void main(String[] args) {  
  8.         // TODO Auto-generated method stub   
  9.             Student st = new Student("张三",10);  
  10.             Student st2 = new Student("李四",20);  
  11.             System.out.println("st的name:" + st.name +", st的age:" + st.age);  
  12.             System.out.println("st2的name:" + st2.name +", st的age:" + st2.age);  
  13.     }  
  14.   
  15. }  
此时系统运行的结果如图:

从运行结果可以看出,我们在实例化Student对象的时候,调用了带参数的构造函数,节省了很多的代码,要注意:如果我们在Student类中定义了一个带参数的构造函数,但是没有写无参的构造函数,这个时候我们在主函数中就不能定义 Student st = new Student();如果在Student类中加上无参的构造函数就可以实现这样的实例化。

相关内容