当前位置:网站首页>2021-05-07构造器
2021-05-07构造器
2022-06-23 09:55:00 【鹿其其鹿】
构造器讲解
类中的构造器也称为构造方法,是进行创建对象的时候必须要调用的,并且构造器有两个特点:
- 必须和类的名字相同
- 必须没有返回类型,也不能写void
一个类即使什么都不写,他也会存在一个构造方法
package oop.demo2;
//java编译之后会生成class文件
public class Person {
//一个类即使什么都不写也会存在一个方法
String name;
//构造器会实例化初始值
//使用new关键字,本质是在调用构造器
//
public Person(){
this.name = "qj";
}
//有参构造 一旦定义有参构造,无参构造就必须显示定义,否则new0实例化对象会报错
public Person(String name){
this.name = name;
}
}
package oop.demo2;
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[]args){
//类:抽象的,实例化
//类实例化后会返回自己的对象
//student对象就是一个Student类的具体实例
Student xiaoming = new Student();
Student xiaohong = new Student();
xiaoming.name = "小明";
xiaohong.age = 18;
System.out.println(xiaoming.name);
System.out.println(xiaohong.age);
//new 实例化了一个对象
Person person = new Person();
System.out.println(person.name);
Person person1 = new Person("kuang");
System.out.println(person1.name);
}
}
构造器:
- 和类名相同
- 没有返回值
作用:
- new本质是在调用构造方法
- 初始化对象的值
注意点:
- 定义有参构造之后,如果想使用无参构造,要显示定义的一个无参构造
- Alt+Insert


边栏推荐
- sql根据比较日期新建字段
- 数学分析_笔记_第2章:实数与复数
- AI系统前沿动态第38期:谷歌已放弃TensorFlow?;训练大模型的四种GPU并行策略;LLVM之父:模块化设计决定AI前途
- 我被提拔了,怎么和原来平级的同事相处?
- On shore experience of Chang'an University majoring in transportation in 2023
- 基於STM32設計的寵物投喂器
- 16. system startup process
- 分布式锁的三种实现方式
- STM32F1与STM32CubeIDE编程实例-红外寻迹传感器驱动
- Centre de calcul haute performance - nvme / nvme - of - nvme - of overview
猜你喜欢

What is BFC? What problems can BFC solve

UEFI source code learning 3.7 - norflashdxe

分布式锁的三种实现方式

启明星辰华典大数据量子安全创新实验室揭牌,发布两款黑科技产品

Comic | code review is driving me crazy!

Web -- Information Disclosure

ICLR 2022 | 视频中的动态卷积TAdaConv以及高效的卷积视频理解模型TAdaConvNeXt

RT thread add MSH command

Typora set up image upload service

Unity技术手册 - 形状(Shape)子模块 - Sprite、SpriteRenderer及生命周期内速度(Velocity over Lifetime)
随机推荐
thymeleaf中如何给onclick事件传值的方法
太无奈!微软停售 AI 情绪识别等技术,直言:“法律跟不上 AI 的发展”
快速排序的简单理解
Year end answer sheet! Tencent cloud intelligent comprehensive strength ranks first in China!
马斯克 18 岁儿子请愿改名,欲断绝父子关系
Gesture recognition based on mediapipe
[GYCTF2020]Blacklist
After the uncommitted transactions in the redo log buffer of MySQL InnoDB are persisted to the redo log, what happens if the transaction rollback occurs? How does the redo log handle this transaction
同花顺推荐么?手机开户安全么?
Cesium loading orthophoto scheme
【CTF】bjdctf_ 2020_ babyrop
regular expression
IPv6 的速度比 IPv4 更快?
mysql innodb 的 redo log buffer 中未 commit 的事务持久化到 redo log 后,万一事务 rollback 了怎么办?redo log 怎么处理这个事务操作?
Bi SQL drop & alter
Distributed common interview questions
正则表达式
Go 单元测试
分布式锁的三种实现方式
J. Med. Chem. | Release: a new drug design model for deep learning based on target structure