Java学习笔记(二) 面向对象---构造函数

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java学习笔记(二) 面向对象---构造函数

Eternity2   2020-01-31 我要评论

面向对象---构造函数

特点

  1. 函数名与类名相同
  2. 不用定义返回值类型
  3. 不写return语句

作用

对象一建立,就对象进行初始化。

具体使用情况

class Student {
    Student(){
        System.out.println("Student run");
    }
}
public class StudentDemo {
    public static void main(String[] args) {
        Student S = new Student();
    }
}

我们在以上代码的Student类中加入了与类同名的构造函数,当我们在创建对象S时,就会自动初始化运行System.out.println("Student run")这一语句,而无需手动调用函数。
程序的运行结果为:

Student run

当在堆内存中产生对象时,对象需要一个初始化动作。当一个类中有我们自己所定义的构造函数时,构造函数会帮助我们完成初始化动作,但是当类中没有构造函数时,则系统会默认给该类中加入一个空参数的构造函数。

构造函数可以重载
一个类中可以有多重名的构造函数,但是多个构造函数之间的参数不能相同。

class Student {
    private String name;
    private int age;
    Student() {
        System.out.println("name="+name+"   age="+age);
    }
    Student(String n) {
        name = n;
        System.out.println("name="+name+"   age="+age);
    }
    Student(int a,String n) {
        age = a;
        name = n;
        System.out.println("name="+name+"   age="+age);
    }
}
public class StudentDemo {
    public static void main(String[] args) {
        Student S1 = new Student();
        Student S2 = new Student("lyx");
        Student S3 = new Student(19,"lyx");
    }
}

运行结果:

name=null   age=0
name=lyx   age=0
name=lyx   age=19

在上述代码中,我们可以发现由于使用的构造函数参数不同,在创建对象时也就调用了不同的构造函数对对象进行初始化。

构造函数和一般函数的不同

  • 写法上不同。
  • 运行上也不同。构造函数在对象一建立时就运行,而一般函数是对象调用才执行。
  • 一个对象建立,构造函数只运行一次,而一般函数可以被对象调用多次。

相应地,一个类中即使有构造函数对对象进行初始化,仍然需要提供公共方法对其访问以便于进行修改和读取。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们