构造方法/构造器
来源:互联网 发布:怎样治疗产后抑郁知乎 编辑:程序博客网 时间:2024/04/30 13:39
构造器就是与类同名的方法,作用在于初始化类的成员变量。
理解构造器之前,首先我们需要知道Java中为什么要引入构造器,以及构造器的作用。假设我们每一次编写一个类都要执行一个initialize()方法,该方法是提醒你,在使用对象之前,应首先调用initialize()方法进行初始化,这就意味着每一用户都能去执行这个方法。Java中引入构造器,确保每一个对象都得到初始化,Java在有能力操作对象之前,系统会自动调用相应的构造器,保证初始化的进行。
构造器最大的用处就是在创建对象时执行初始化,当创建一个对象时,系统会为这个对象的实例进行默认的初始化。如果想改变这种默认的初始化,就可以通过自定义构造器来实现(重载构造器)。
// 在Java中如果不写构造方法的话,会默认加上一个无参数的构造方法public ClassName(){}
package com.execute.demo;public class Account {// 类的成员变量private int id;private String username;private String password;// getters and setters omitted// 在Java中如果不写构造方法的话, 会默认加上一个无参数的构造方法// 但是如果已经有了一个有参数的构造方法, 那么无参数的构造方法就不会默认被加上// 如果重载了有参数的构造方法, 就最好加一个无参数的构造方法(以备不时之需嘛)public Account() {}// 重载构造方法(有参构造)public Account(int id, String username, String password) {super();this.id = id;this.username = username;this.password = password;}@Overridepublic String toString() {return "Account [id=" + id + ", username=" + username + ", password=" + password + "]";}public static void main(String[] args) {// 调用无参构造方法(这里不报错,是因为类里面写了无参构造,如果没有无参构造,则new Account()报错)Account account = new Account();// set方式赋值, 当然也可以用原始的 对象.属性 的方式, 进行赋值account.id = 1000;account.setUsername("a");account.setPassword("123456");System.out.println("无参构造");System.out.println(account.toString());// 调用有参构造方法, 同时对类的成员变量进行初始化, 省略很多代码量System.out.println("有参构造");Account aAccount = new Account(1001, "b", "142857");Account bAccount = new Account(1002, "c", "715482");System.out.println(aAccount.toString());System.out.println(bAccount.toString());}/** * 1.什么时候会用到构造方法? new一个对象的时候 * 2.new Account()调用无参构造, new Account(id, username, password)调用有参构造 * 3.如果已经有了一个有参数的构造方法, 那么无参数的构造方法就不会默认被加上 * 如果Account类中只有一个有参数的构造方法, 这时再使用Account account = new Account();来创建对象的时候就会出错 * 避免出错, 则需要将无参构造方法加上, 这就是为什么书上要强调写了有参数的构造方法就最好加一个无参数的构造方法(qwq嘤嘤嘤嘤) */}打印结果:
无参构造Account [id=1000, username=a, password=123456]有参构造Account [id=1001, username=b, password=142857]Account [id=1002, username=c, password=715482]
0 0
- 构造器(构造方法)
- 构造方法/构造器
- 构造方法 构造器 构造函数
- 构造器(构造方法)
- Java构造器(构造方法)的使用
- scala 构造方法(默认构造器)
- JAVA的构造器和构造方法
- JAVA的构造器和构造方法
- 构造器(构造方法)问题
- 构造器与构造方法的区别
- 重写与重载,构造器,构造方法
- 构造器 &&方法
- 构造方法也叫做构造函数OR构造器
- 构造方法
- 构造方法
- 构造方法
- 构造方法
- 构造方法
- #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif 语句解释
- SELinux policy问题解决思路总结
- 12.2 布局管理器简介
- Linux 用户和用户组
- MVP实战心得(三)---封装Retrofit2.0+RxAndroid+RxBus
- 构造方法/构造器
- Xshell xftp 代理设置
- Expression Add Operators
- 12.3 文本输入
- runtime exception 与checked exception区别
- Ubuntu系统学习笔记-5.测试jdbc
- 11.4 选择组件
- java基础常忘又常用代码
- [Android测试] AS+Appium+Java+Win 自动化测试之十:testng多设备并行测试实例封装