一直对重载和构造函数的概念不是很理解,看了mars的视频以后有一种豁然开朗的感觉,写下来跟大家一起分享下。
方法的重载有3个条件:1、函数位于同一个类下面;2、方法名必须一样;3、方法的参数列表不一样。比如有以下的例子:
- class Student {
- void action(){
- System.out.println("该函数没有参数!");
- }
- void action(int i)
- {
- System.out.println("有一个整形的参数!");
- }
- void action(double j)
- {
- System.out.println("有一个浮点型的参数!");
- }
- }
该类中定义了3个方法,但是3个方法的参数列表不一样; 下面在主函数中调用这个类:- public class Test {
-
- /**
- * @param args
- * @author weasleyqi
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Student st = new Student();
- st.action();
- st.action(1);
- st.action(1.0);
- }
-
- }
看看运行结果: 从控制台的输出可以看出,我在主函数中实例化一个student对象,分别调用了这个对象的3中方法,由于3个方法的参数不一样,所以可以看到输出的结果也不一样;
构造函数的使用:定义一个Sutdent类,类里面定义两个属性:
- class Student {
-
- String name;
- int age;
- }
此时的Student类中没有构造函数,系统会自动添加一个无参的构造函数,这个构造函数的名称必须和类的名称完全一样,大小写也必须相同,系统编译完了之后是以下的情况:
- class Student {
- Student()
- {
- }
- String name;
- int age;
- }
主函数中实例化两个对象:
- public class Test {
- /**
- * @param args
- * @author weasleyqi
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Student st = new Student();
- st.name = "张三";
- st.age = 10;
-
- Student st2 = new Student();
- st2.name = "李四";
- st2.age = 20;
- }
- }
从主函数可以看出,此时的Student对象的属性比较少,创建的实例也比较少,如果属性多再创建多个实例的话,这个代码的量就很大,这时候,我们可以
添加一个带参数的构造函数,如下:
- class Student {
- Student(String n, int a)
- {
- name = n;
- age = a;
- }
- String name;
- int age;
- }
主函数的代码如下:
- public class Test {
-
- /**
- * @param args
- * @author weasleyqi
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Student st = new Student("张三",10);
- Student st2 = new Student("李四",20);
- System.out.println("st的name:" + st.name +", st的age:" + st.age);
- System.out.println("st2的name:" + st2.name +", st的age:" + st2.age);
- }
-
- }
此时系统运行的结果如图: 从运行结果可以看出,我们在实例化Student对象的时候,调用了带参数的构造函数,节省了很多的代码,
要注意:如果我们在Student类中定义了一个带参数的构造函数,但是没有写无参的构造函数,这个时候我们在主函数中就不能定义 Student st = new Student();如果在Student类中加上无参的构造函数就可以实现这样的实例化。