目录
1.1简单认识类
类是用来对一个实体(对象)进行描述的。
1.2.类的格式
属性是用来描述类的,方法主要说明类具有哪些功能的。
注意:类名采用大驼峰定义,成员名前写public,并且public后不带static 。
2.1类的实例化
public class Test {
public static void main(String[] args) {
Student S1 = new Student();
S1.name = "张三";
S1.age = 15;
S1.studentNum = 20211111;
S1.doClass();
}
}
注意:
①使用new关键字用于创建一个对象的实例化;并且可以用new实例化多个对象。
②通过new实例化对象时,成员变量会有一个默认值(在本文最后表格中)。
③使用 . 操作符来访问对象中的属性和方法。
2.2类和对象的说明
①类是一个模型一样的东西,用来对一个实体进行描述,限定了类有哪些成员。
②类是一种自定义类型,可以用来定义变量。
③一个类可以实例化多个对象,实例化出的对象,占用实际的物理空间,存储成员变量。
3.this 的引用
public class Date{
public int year;
public int month;
public int day;
public void setDay(int year,int month,int day){
this.year = year;
this.month = month;
this.day = day;
this.printDate();
}
public Date(){
this(1599,15,6);
}
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printDate(){
System.out.println(this.year+"/"+
this.month+"/"+this.day);
}
public static void main(String[] args) {
Date d1 = new Date();
d1.setDay(1822,5,8);
d1.printDate();
}
}
①通过 this 访问当前对象的成员变量
如果不加此 this ,则形参自己给自己赋值,并没有赋值到对象当中,同时输出默认值。
②通过 this 访问当前对象的非静态的成员方法
再介绍③之前,先简单说一下构造方法(后文会再讲到):构造方法(构造器)是一个特殊的成员方法,名字必须与类型名相同,在创建对象的时候,由编译器自动调用,并且在整个对象的声明周期只能使用一次。
作用:初始化成员变量且不止一个构造方法。
注意:构造方法没有返回值,写成void也不行。
③构造方法中,可以通过 this 调用其他构造方法简化代码
此处通过this 调用带有三个参数的构造方法。
注意:this()必须是无参数构造方法中的第一条语句。
4.1再谈构造方法
可以借助IDEA来快速生成:右击空白处→选择Generate→选择Constructor→选择你要构造的字段
public class Date{
public int year;
public int month;
public int day;
public Date(){
// this(1599,15,6);
this.year = 1900;
this.month = 52;
this.day = 55;
}
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printDate(){
System.out.println(this.year+"/"+
this.month+"/"+this.day);
}
public static void main(String[] args) {
Date d1 = new Date();
// d1.setDay(1822,5,8);
d1.printDate();
}
}
特性:
①名字必须与类名相同。
②没有返回值,设置成 void 也不行。
③创建对象时由编译器自动调用,并去在整个对象的声明周期只能使用一次。
④构造方法可以重载:
⑤如果用户没有显示定义,则编译器会自己生成一份默认的构造方法,生成的默认的构造方法一定是无参数的(注意:一旦用户定义,编译器则不再生成)。
⑥构造方法中,可以通过 this 调用其他构造方法来简化代码。
无参数构造方法,其内部给各个成员赋初始值,该部分功能与带有三个参数的构造方法重复。此处可以在无参数构造方法中通过 this 调用带有三个参数的构造方法。但是 this() 必须在构造方法中的第一条语句。
4.2默认初始化
new关键字在当前代码的作用:
①检测对象的类是否被加载了
②为对象分配内存空间
③处理并发安全问题
④初始化所分配的空间(初始值)
⑤设置对象头信息
⑥调用构造方法,给对象中的各个成员赋值
4.3就地初始化
在代码编译完成过i后,编译器会将所有成员初始化的这些语句添加到各个构造方法中
默认值:
数据类型 | 默认值 |
byte | 0 |
char | /u0000' |
short | 0 |
int | 0 |
long | 0L |
boolean | FALSE |
float | 0.0f |
double | 0 |
reference | null |
本次文章会分为多次发布