一直对重载和构造函数的概念不是很理解,看了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("有一个浮点型的参数!");
- }
- }
下面在主函数中调用这个类:
- 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;
- }
- 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;
- }
- }
- 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);
- }
- }
- st的name:张三, st的age:10
- st2的name:李四, st的age:20
从运行结果可以看出,我们在实例化Student对象的时候,调用了带参数的构造函数,节省了很多的代码,要注意:如果我们在Student类中定义了一个带参数的构造函数,但是没有写无参的构造函数,这个时候我们在主函数中就不能定义 Student st = new Student();如果在Student类中加上无参的构造函数就可以实现这样的实例化。