7类和对象

```

public class Test2 {

//语法,class 类名{}

}

class WashMachine{

//字段/属性

//方法

//放在类里面,方法外面,叫字段,属性,成员变量

public String brand;

public String type;

//接下来就是行为,成员方法

}

//可以有若干的属性,方法//类名使用大驼峰,即首字母大写

class Dog{

public String name;

public String color;

public void eat(){//为什么没有static

System.out.println("吃狗粮");

}

}

//建议一个文件一个类,现在不符合,现在很多个类

//知道如何定义类

//那怎么用

```

![[Pasted image 20251208163740.png]]

![[Pasted image 20251208164933.png]]

```

class Dog {

String name;

int age;

public void eat() {

System.out.println(name+" is eating");

}

/*Dog(String name, int age) {

this.name = name; this.age = age;*/ // }}

public class Test {

//由类生成对象的过程,就叫做实例化

public static void main(String[] args) {

int a=0;

Dog dog=new Dog();//new一个对象,对象的实例化

//创建好对象,怎么使用对象

// dog.age

// dog.name System.out.println(dog.name);//没有值

System.out.println(dog.age);

}

}

```

```

String name;//成员有默认值//引用变量,null

int age;//基本数据类型,默认为对应0,0

```

![[Pasted image 20251208165635.png]]

![[Pasted image 20251208170102.png]]可以关键字new实例化多个对象

类和对象的说明

  1. 类只是一个模型一样的东西,用来对一个实体进行描述,限定了类有哪些成员.

  2. 类是一种自定义的类型,可以用来定义变量.

  3. 一个类可以实例化出多个对象,实例化出的对象 占用实际的物理空间,存储类成员变量

  4. 做个比方。类实例化出对象就像现实中使用建筑设计图建造出房子,类就像是设计图,只设计出需要什么东 西,但是并没有实体的建筑存在,同样类也只是一个设计,实例化出的对象才能实际存储数据,占用物理空 间

```

public class Date {

//日期

public int year;

public int month;

public int day;//public以后讲

public void printDate() {

System.out.println(year+"年"+month+"月"+day+"日");

}

//写一个方法,来设置年月日

public void setDate(int year,int month,int day) {

this.year=year;

this.month=month;

this.day=day;

}

static void main(String[] args) {

Date date=new Date();

date.setDate(2025,12,8);

date.printDate();

}

}

```

![[Pasted image 20251208171629.png]]

![[Pasted image 20251208172245.png]]

怎么解!!当形参名和成员变量名时,输出的结果都是0!!

因为局部变量优先使用,所以这仨都是一个,到头来成员变量没有赋值

```

public void setDate(int year,int month,int day) {

year=year;

month=month;

day=day;

}

```

那怎么解决,就是加this.

![[Pasted image 20251208191414.png]]

```

this.year=year;

this.month=month;

this.day=day;

}

```

this 到底代表什么

代表当前对象的引用,说明是当前对象,怎么判断当前对象,就比如

```

public void setDate(int year,int month,int day) {

this.year=year;

this.month=month;

this.day=day;

}

static void main(String[] args) {

Date date=new Date();

date.setDate(2025,12,8); //这里的date

date.printDate();

Date date1=new Date();

date.setDate(2026,12,8); //这里的date就是上面的this

date.printDate();

```

![[Pasted image 20251208192424.png]]

![[Pasted image 20251208193433.png]]

this的特性

  1. this的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型

  2. this只能在"成员方法"中使用

  3. 在"成员方法"中,this只能引用当前对象,不能再引用其他对象

this的用法有三种

1 可以通过this 访问当前对象的成员变量

2 可以通过this 访问当前对象的非静态的成员方法

3 可以通过this 访问当前对象的其他构造方法

public class Date {

public Date(){

System.out.println("这是不带参数的构造方法" );

}

//构造方法,没有返回值,方法名和当前类名一样,

//方法名 (形参列表){

// 方法体

// }

![[Pasted image 20251208205827.png]]

![[Pasted image 20251208205843.png]]

```

public Date(int year,int month,int day){

this.year = year;

this.month = month;

this.day = day;

}

//构造方法可以重载,不止一个//构造方法最大的作用,1,不止一个,2,初始化对象当中的成员

```

![[Pasted image 20251208212311.png]]

//java会帮我写一个没有任何参数的构造方法

```

public Date()){

// this.year = year;

//this.month = month;

//this.day = day;

}

```

前提是没有任何构造方法,如果有其他构造方法,就不可以,救急不救穷

本节要学会

1 定义类和创建对象

2 会访问对象当中的成员变量和成员方法

3 明白this 是干嘛的

4 明白构造方法是干嘛的

```

| |

|---|

|class WashMachine {|

||//字段 、属性、 成员变量|

||public String brand; // 品牌|

||public String type; // 型号|

||public double weight; // 重量|

||public double length; // 长|

||public double width; // 宽|

||public double height; // 高|

||public String color; // 颜色|

|||

||//行为 、成员方法|

||public void washClothes(){ // 洗衣服|

||System.out.println("洗衣功能");|

||}|

||public void dryClothes(){ // 脱水|

||System.out.println("脱水功能");|

||}|

||public void setTime(){ // 定时|

||System.out.println("定时功能");|

||}|

||}|

||//类 -》 类型 -> 自定义的类型|

||class Dog {|

||public String name;|

||public int age;|

|||

||public void eat() {|

||System.out.println(name+"吃狗粮");|

||}|

||}|

|||

||public class Test2 {|

|||

||public void test() {|

||System.out.println("test.....");|

||}|

|||

||public static void main(String[] args) {|

||Test2 test2 = new Test2();|

||test2.test();|

|||

|||

||//test();|

||}|

|||

||public static void main1(String[] args) {|

||Dog dog = new Dog();|

||dog.name = "小黑";|

||dog.age = 1;|

||dog.eat();|

||System.out.println(dog.name);|

||System.out.println(dog.age);|

||System.out.println("=============");|

|||

||Dog dog2 = new Dog();|

||dog2.name = "小黄";|

||dog2.age = 10;|

||dog2.eat();|

||System.out.println(dog2.name);|

||System.out.println(dog2.age);|

|||

|||

||/*int a;|

||System.out.println(a);*/|

||}|

||}|

```

`this.`的用法详解

`this.`用于**访问当前对象的成员**,它的位置规则比 `this()`灵活得多。

1. 基本用法

```

public class Student {

private String name; // 实例变量

private int age;

public Student(String name, int age) {

// 使用 this. 区分参数和实例变量

this.name = name; // this.name 是实例变量,name 是参数

this.age = age; // this.age 是实例变量,age 是参数

}

public void printInfo() {

// 访问当前对象的成员

System.out.println("姓名:" + this.name);

System.out.println("年龄:" + this.age);

}

}

```

2. 位置规则(非常灵活)

`this.`可以在类的**任何非静态上下文中使用**:

✅ 可以在方法中

```

public void setName(String name) {

this.name = name; // ✅ 在实例方法中

}

```

✅ 可以在构造方法中(`this()`之后)

```

public Student(String name) {

this(name, 18); // ✅ 先调用其他构造(必须是第一条)

this.printInfo(); // ✅ 之后可以使用 this. 调用方法

}

```

✅ 可以在代码块中

```

public class Example {

private int x = 10;

{

// 实例初始化块

System.out.println("x = " + this.x); // ✅

}

}

```

3. 主要使用场景

场景1:解决名称冲突

```

public class Employee {

private String name; // 实例变量

private double salary;

public void setName(String name) { // 参数 name

this.name = name; // ✅ 左边是实例变量,右边是参数

}

public void setSalary(double salary) {

// salary = salary; // ❌ 错误:只是参数赋值给自己

this.salary = salary; // ✅ 正确:参数赋值给实例变量

}

}

```

场景2:链式调用(Builder模式)//不认识

```

public class Person {

private String name;

private int age;

public Person setName(String name) {

this.name = name;

return this; // 返回当前对象

}

public Person setAge(int age) {

this.age = age;

return this; // 返回当前对象

}

}

// 使用

Person p = new Person()

.setName("张三")

.setAge(25); // 链式调用

```

场景3:调用当前对象的其他方法

```

public class Calculator {

private int value;

public void add(int x) {

this.value += x; // 使用 this. 访问字段

this.print(); // 使用 this. 调用方法

}

public void print() {

System.out.println("当前值:" + this.value);

}

}

```

场景4:作为参数传递

```

public class Button {

private String text;

public void addClickListener() {

// 将当前对象作为参数传递

EventManager.register(this);

}

public void onClick() {

System.out.println("按钮被点击: " + this.text);

}

}

```

4. 与 `this()`的位置对比

```

public class User {

private String username;

private String email;

public User() {

// 1. 这里必须是 this() 或 super(),不能是 this.

this("默认用户"); // ✅ 必须是第一条

}

public User(String username) {

// 2. 构造方法中,this() 必须在最前面

this(username, "default@email.com"); // ✅

// 3. this() 之后,可以使用 this.

this.printInfo(); // ✅

}

public User(String username, String email) {

// 4. 没有 this() 时,可以直接用 this.

this.username = username; // ✅

this.email = email; // ✅

}

public void updateEmail(String email) {

// 5. 普通方法中,可以任意位置使用 this.

if (email != null) {

this.email = email; // ✅

}

this.sendNotification(); // ✅

}

}

```

5. 什么时候可以省略 `this.`

```

public class Product {

private String name;

private double price;

public Product(String name, double price) {

// 必须用 this.,因为参数名和实例变量名相同

this.name = name;

this.price = price;

}

public double calculateTotal(int quantity) {

// 可以省略 this.,因为没有名称冲突

return price * quantity; // price 就是 this.price

}

public void display() {

// 也可以写成,更清晰

System.out.println("产品: " + this.name);

System.out.println("价格: " + this.price);

}

}

```

6. 特殊用法:内部类中访问外部类

```

public class Outer {

private String outerField = "外部字段";

class Inner {

private String innerField = "内部字段";

public void print() {

System.out.println(innerField); // 自己的字段

System.out.println(this.innerField); // 明确访问自己的字段

System.out.println(outerField); // 外部类的字段

System.out.println(Outer.this.outerField); // ✅ 明确访问外部类字段

}

}

}

```

7. 常见错误

❌ 在静态上下文中使用

```

public class Test {

private int x = 10;

public static void staticMethod() {

// System.out.println(this.x); // ❌ 错误:静态方法中不能使用 this

}

}

```

❌ 在 main 方法中使用

```

public class Main {

private String name = "Test";

public static void main(String[] args) {

// System.out.println(this.name); // ❌ 错误:main 是静态方法

}

}

```

8. 总结对比

|特性|`this()`|`this.`|

|---|---|---|

|**用途**​|调用本类其他构造方法|访问当前对象成员|

|**位置限制**​|必须是构造方法第一条语句|几乎任何地方(非静态上下文中)|

|**使用场景**​|构造方法重载、代码复用|解决名称冲突、链式调用、访问成员|

|**能否在静态方法中使用**​|不能|不能|

|**调用次数**​|一次(每个构造方法只能调用一次)|多次(可以多次使用)|

**简单记忆:**

  • `this()`→ 只在构造方法中,且必须是**第一条语句**

  • `this.`→ 任何地方(除了静态上下文),用于**访问当前对象的成员**

我来详细解释 Java 中 `this()`构造方法调用的位置规则。

1. 基本规则

**`this()`调用必须是构造方法中的第一条语句**

```

public class Person {

private String name;

private int age;

public Person() {

// this() 必须是第一条语句

this("无名氏", 18); // ✅ 正确

// 其他代码...

}

public Person(String name, int age) {

this.name = name;

this.age = age;

}

}

```

2. 常见错误示例

❌ 错误:`this()`不是第一条语句

```

public Person() {

System.out.println("创建Person对象"); // 错误:在 this() 之前

this("无名氏", 18); // ❌ 编译错误

}

```

❌ 错误:`this()`和 `super()`同时存在

```

public Person() {

super(); // 错误:不能同时有 this() 和 super()

this("无名氏", 18); // ❌ 编译错误

}

```

3. 正确用法示例

✅ 正确:构造方法重载

```

public class Rectangle {

private int width;

private int height;

// 无参构造

public Rectangle() {

this(10, 10); // ✅ 调用有参构造

}

// 一个参数构造

public Rectangle(int size) {

this(size, size); // ✅ 调用两个参数构造

}

// 两个参数构造(主构造)

public Rectangle(int width, int height) {

this.width = width;

this.height = height;

}

}

```

✅ 正确:带验证的构造

```

public class BankAccount {

private String owner;

private double balance;

public BankAccount(String owner) {

this(owner, 0.0); // ✅ 调用两个参数的构造

}

public BankAccount(String owner, double initialBalance) {

// 参数验证

if (owner == null || owner.trim().isEmpty()) {

throw new IllegalArgumentException("账户名不能为空");

}

if (initialBalance < 0) {

throw new IllegalArgumentException("初始余额不能为负");

}

this.owner = owner;

this.balance = initialBalance;

}

}

```

4. 为什么有这样的限制?

  1. **对象初始化顺序**:确保父类构造先于子类构造执行

  2. **避免重复初始化**:防止字段被多次初始化

  3. **保证对象一致性**:确保对象在构造完成前处于一致状态

5. 特殊技巧:使用静态工厂方法

如果需要更复杂的初始化逻辑,可以使用静态工厂方法:

```

public class ComplexObject {

private final String data;

private ComplexObject(String data) {

this.data = data;

}

// 静态工厂方法,可以有复杂逻辑

public static ComplexObject create(String input) {

// 可以在调用构造方法前做各种处理

if (input == null) {

input = "default";

}

String processed = processInput(input);

// 最后调用私有构造

return new ComplexObject(processed);

}

private static String processInput(String input) {

return input.trim().toUpperCase();

}

}

```

6. 总结

|规则|说明|

|---|---|

|必须是第一条语句|`this()`必须在构造方法的第一行|

|不能和 `super()`共存|一个构造方法只能调用 `this()`或 `super()`之一|

|只能调用一次|一个构造方法只能有一个 `this()`调用|

|不能递归调用|不能形成构造方法的无限递归|

|必须在构造方法中|只能在构造方法中使用 `this()`|

记住这个简单规则:**如果你要在构造方法中使用 `this()`调用其他构造,它必须是该构造方法的第一条且唯一的构造调用语句。**

![[Pasted image 20251209191145.png]]

实例化对象的时候一定会调用构造方法

如果当前类当中没有任何构造方法吗Java会默认一个不带参数的构造方法

构造方法的核心作用,初始化对象状态

4. 构造方法 vs 普通方法

|对比点|构造方法|普通方法|

|---|---|---|

|**调用时机**​|创建对象时自动调用|需要显式调用|

|**调用方式**​|`new ClassName()`|`object.methodName()`|

|**名称**​|必须与类名相同|任意合法标识符|

|**返回值**​|没有返回值类型(连void都没有)|有返回值类型(或void)|

|**继承**​|不被子类继承|被子类继承(除非private)|

|**默认提供**​|不写时提供默认无参构造|不提供默认方法|

![[Pasted image 20251209201040.png]]

![[Pasted image 20251209201058.png]]

对面向对象的语言来说,有几个重要特性,封装,继承,多态

是面向对象的特征

  1. 封装

```

class Student {

private String name;

public int age;

public String sutNum;

```

封装就是对成员变量,或成员方法,使用private进行修饰

这可以让成员变量或者成员方法只能在类当中使用,

public

private

protected,都是管使用权限的(在类内,在包内,,,)

```

class Student {

private String name;//只能在class Student这个类内使用

public int age;

public String sutNum;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}//上有政策,下有对策,即使private也能使用,即使封装也能使用

public class Test{

public static void main(String[] args) {

//对象的实例化

Student s1 = new Student();

Student s2 = new Student("zhagnsan",10,"1234");

s1.getName();

s2.setName("zhangsan");

}

```

```

private void eat(){//在本类服务,不对外公开

//其他业务操作

System.out.println(name+"Eating");

}

public void sleep(){

eat();//这样子就可以,但是不知道里面是什么,细节不知道

System.out.println(name+"Sleeping");

}

```

![[Pasted image 20251209204035.png]]

private是只能在包的类中使用

default是可以在包中使用

```

void setSutNum(String sutNum) {

this.sutNum = sutNum;

}

```

public是都可以

包就是文件夹啊

```

//import java.util.Arrays;//导入路径

import java.util.*;//也可以这样子,不建议

import java.util.Date;

int[]array={1,2,3};

System.out.println(java.util.Arrays.toString(array));要不导包要不写一边,写导包!!

Date d = new Date();

java.sql.Date sqlDate = new java.sql.Date(d.getTime());//这个就不能导包了,只能写在前面

```

当两个访问的包有两个Date,其中一个就只能服务

总结

![[Pasted image 20251209213818.png]]

//自定义包

![[Pasted image 20251209220035.png]]

为什么!!!

![[Pasted image 20251209220100.png]]

![[Pasted image 20251209220602.png]]

假如我们都是1班的

那么就不修改这个

```

| |

|---|

|public class Test {|

|||

||public static void main(String[] args) {|

||//Student.className = "1班";|

|||

|||

||Student student1 = null;|

||/*student1.className = "1班";|

||System.out.println(student1.className );|

||*/|

||System.out.println(student1.name);|

||}|

|||

||public static void main6(String[] args) {|

|||

||Student student1 = new Student("zhangsan",10,"1234");|

||//student1.className = "1班";|

|||

|||

||Student.className = "1班";|

|||

||student1.show();|

|||

||Student student2 = new Student("lisi",12,"12348");|

|||

||student2.show();|

|||

||}|

```

![[Pasted image 20251209221127.png]]

![[Pasted image 20251209221144.png]]

我们尽量用Student.classname

不用s1.classname

![[Pasted image 20251209221338.png]]

静态不依赖对象,不需要对象的引用,内存都省了

![[Pasted image 20251209221719.png]]

```

class Date {

private int x;

private int y;

private Date(int x, int y) {//提供一个构造方法

this.x = x;

this.y = y;

}

public int getX() {

return x;

}

public void setX(int x) {

this.x = x;

}

public int getY() {

return y;

}

public void setY(int y) {

this.y = y;

}

/* void main(String[] args) {

Date d1 = new Date(1, 2);

Date d2 = new Date(3, 4);

*/

}

/*void main(String[] args) {

Date d1 = new Date(1,2);

Date d2 = new Date(3,4);

}*/

//这个为什么可以!!

public class Test {

static void main(String[] args) {

//这样子就不可以 Date d1=new Date(1,2);

// Date d1=new Date(1,2);

// System.out.println(Date.getX());要受不了了我问ai

}

}

```

我来帮你分析图中的代码问题,并解答"这个为什么可以"的疑问。

问题分析

1. 你的代码问题

```

class Date {

private int x;

private int y;

// 构造方法是 private 的!

private Date(int x, int y) { // ❌ 问题在这里

this.x = x;

this.y = y;

}

// ... 其他方法

}

```

```

public class Test {

static void main(String[] args) {

Date d1 = new Date(1, 2); // ❌ 编译错误!

}

}

```

**错误原因**:

`Date`类的构造方法是`private`的,这意味着:

  • 只能在`Date`类**内部**创建对象

  • 在其他类(如`Test`类)中**不能**使用`new Date(1, 2)`

2. 你看到的"可以"的情况

你可能在某些IDE或工具中看到这种语法:

```

Date d1 = new Date(x: 1, y: 2);

```

这是某些IDE(如IntelliJ IDEA)的特性,**不是标准的Java语法**:

  • IDE可能会显示这种语法帮助理解参数含义

  • 但实际编译时,Java会把它当作普通构造方法调用`new Date(1, 2)`

  • 如果构造方法是`private`,这种写法**同样会编译失败**

解决方案

方案1:将构造方法改为public(推荐)

```

class Date {

private int x;

private int y;

// 改为 public

public Date(int x, int y) { // ✅

this.x = x;

this.y = y;

}

// ... 其他方法

}

```

方案2:在Date类内部创建对象

```

class Date {

private int x;

private int y;

private Date(int x, int y) {

this.x = x;

this.y = y;

}

// 提供静态工厂方法

public static Date createDate(int x, int y) { // ✅

return new Date(x, y);

}

}

public class Test {

static void main(String[] args) {

d1 = Date.createDate(1, 2); // ✅ 这样可以

}

}

```

方案3:完整的可运行代码

```

class Date {

private int x;

private int y;

// 1. 构造方法改为 public

public Date(int x, int y) {

this.x = x;

this.y = y;

}

public int getX() {

return x;

}

public int getY() {

return y;

}

}

public class Test {

public static void main(String[] args) {

// 2. 正常创建对象

Date d1 = new Date(1, 2); // ✅ 可以

Date d2 = new Date(3, 4); // ✅ 可以

// 3. 获取值

System.out.println("d1: x=" + d1.getX() + ", y=" + d1.getY());

System.out.println("d2: x="2.getX() + ", y=" + d2.getY());

}

}

```

重要概念总结

  1. **构造方法的访问修饰符**:
  • `public`:任何类都可以调用

  • `private`:只能在本类内部调用

  • `protected`:同包或子类可以调用

  • 默认(不写):同包内可以调用

  1. **你困惑的根源**:
  • 你看到的`new Date(x: 1, y: 2)`是**IDE的显示特性**,不是标准Java语法

  • 实际Java编译器看到的是`new Date(1, 2)`

  • 因为构造方法是`private`,所以**无论哪种写法都会失败**

  1. **正确的调用方式**:

```

// 标准Java语法

Date d1 = new Date(1, 2);

// 某些IDE可能会显示为(但实际相同):

Date d1 = new Date(x: 1, y: 2);

```

最终建议

修改你的`Date`类,将构造方法的`private`改为`public`:

```

// 修改这一行

public Date(int x, int y) { // 把 private 改为 public

this.x = x;

this.y = y;

}

```

这样你的`Test`类中的`new Date(1, 2)`就可以正常工作了。

哦,明白了!你是在问**第一个构造方法中,`this.name = name`的 `name`是从哪里来的**。

java

下载

复制

运行

```

public Student(String name, int age, double score) {

this.name = name; // 将参数值赋给成员变量

this.age = age;

this.score = score;

}

```

参数来源:

**这些参数来自创建对象时的传参**:

java

下载

复制

运行

```

// 这里传入的参数会传给构造方法

Student student1 = new Student("lisi", 10, 98.5);

// ↑ ↑ ↑ ↑

// 对应构造方法参数

// String name, int age, double score

```

执行过程分解:

  1. **创建对象时传入参数**

java

下载

复制

运行

```

Student student1 = new Student("lisi", 10, 98.5);

```

  1. **参数传递给构造方法**
  • 构造方法接收到:`name = "lisi"`, `age = 10`, `score = 98.5`
  1. **构造方法内部赋值**

java

下载

复制

运行

```

public Student(String name, int age, double score) {

this.name = "lisi"; // 参数 name 的值是 "lisi"

this.age = 10; // 参数 age 的值是 10

this.score = 98.5; // 参数 score 的值是 98.5

}

```

更清晰的写法(用不同变量名):

java

下载

复制

运行

```

class Student {

private String studentName; // 成员变量

private int studentAge;

private double studentScore;

// 参数名和成员变量名可以不同

public Student(String n, int a, double s) {

studentName = n; // 不需要 this,因为变量名不同

studentAge = a;

studentScore = s;

}

}

```

对比两种写法:

写法1:用 this(推荐)

java

下载

复制

运行

```

public Student(String name, int age, double score) {

this.name = name; // 左边的 name 是成员变量

// 右边的 name 是参数

}

```

写法2:用不同变量名

java

下载

复制

运行

```

public Student(String n, int a, double s) {

name = n; // 不需要 this,因为 name 是成员变量

// n 是参数

age = a;

score = s;

}

```

实际使用:

java

下载

复制

运行

```

public class Test {

public static void main(String[] args) {

// 创建不同学生对象

Student s1 = new Student("张三", 20, 90.5);

Student s2 = new Student("李四", 19, 88.0);

Student s3 = new Student("王五", 21, 95.5);

// 每个对象的初始化值都不同

// s1: name="张三", age=20, score=90.5

// s2: name="李四", age=19, score=88.0

// s3: name="王五", age=21, score=95.5

}

}

```

**简单说**:第一个构造方法中的 `name`、`age`、`score`是**参数**,它们的值来自 `new Student(...)`时括号里传入的值。构造方法的作用就是把这些传入的值赋给对象的成员变量。

那用this()的是怎么写的,和this.的区别是什么

好的,这是两个完全不同的概念:

1. `this.`和 `this()`的区别

|对比项|`this.`|`this()`|

|---|---|---|

|**类型**​|引用(指向当前对象)|方法调用(调用本类其他构造方法)|

|**作用**​|访问当前对象的成员变量或方法|在一个构造方法中调用另一个构造方法|

|**位置**​|构造方法或实例方法的任何地方|必须是构造方法的第一行代码|

|**例子**​|`this.name = name;`|`this("张三", 20, 90.5);`|

2. 使用 `this.`的例子

java

下载

复制

运行

```

class Student {

private String name;

private int age;

public void setName(String name) {

this.name = name; // 这里的 this.name 是成员变量

// 右边的 name 是参数

}

public void showInfo() {

System.out.println("姓名:" + this.name); // 可以省略 this

System.out.println("年龄:" + this.age); // 推荐加上,更清晰

}

}

```

3. 使用 `this()`的例子//如果构造方法没有参数就不能使用

情况1:一个构造方法调用另一个构造方法

java

下载

复制

运行

```

class Student {

private String name;

private int age;

private double score;

// 完整的构造方法

public Student(String name, int age, double score) {

this.name = name;

this.age = age;

this.score = score;

}

// 只传名字,使用默认年龄和分数

public Student(String name) {

this(name, 18, 60.0); // 调用上面的构造方法

// 注意:这必须是第一行!

}

}

```

情况2:更复杂的例子

java

下载

复制

运行

```

class Student {

private String name;

private int age;

private double score;

private String school;

// 最完整的构造方法

public Student(String name, int age, double score, String school) {

this.name = name;

this.age = age;

this.score = score;

this.school = school;

}

// 缺少学校,默认为"北京大学"

public Student(String name, int age, double score) {

this(name, age, score, "北京大学");

}

// 只有名字和年龄

public Student(String name, int age) {

this(name, age, 60.0, "北京大学"); // 分数默认60

}

// 只有名字

public Student(String name) {

this(name, 18, 60.0, "北京大学");

}

}

```

静态成员方法

```

//静态成员方法

public static String getClassname() {

return classname;

}

public class Test {

static void main(String[] args) {

Student student1=new Student("lisi",10,98.5);

student1.showClass();

System.out.println(Student.getClassname());//静态大一级,不依赖对象

}

}

```

![[Pasted image 20251210171435.png]]

![[Pasted image 20251210171716.png]]

![[Pasted image 20251210171851.png]]

```

public void showClass(){

System.out.println("姓名"+this.name+"年龄"+this.age);

getClassname();

}

//静态成员方法

public static String getClassname() {

return classname;

}

```

静态方法的特性,

  1. 不属于某个具体的对象,是类方法

  2. 可以通过对象调用,也可以通过类名.静态方法名调用,推荐第二个

  3. 不能在静态方法中访问任何非静态成员变量(this)是非静态变量,不能用

![[Pasted image 20251210172328.png]]

静态成员变量 的初始化

  1. 就地初始化(直接赋值)

  2. 通过get,set方法初始化

  3. 构造方法初始化//用的相对少

  4. (使用代码块初始化)

代码块:静态代码块,非静态代码块(实例代码块)(构造代码块),同步代码块

![[Pasted image 20251210173409.png]]

先执行的是静态代码块 ,再执行实例代码块,然后才是构造方法

![[Pasted image 20251210173704.png]]

//实例代码块需要实例一个对象

```

Student student1=new Student("lisi",10,98.5);

{

this.name="she";

System.out.println("this.name="+this.name);

}//在类里面

```

![[Pasted image 20251210202314.png]]

//同个类型的就按顺序

代码块是用发来初始化的

#对象的打印

![[Pasted image 20251210205308.png]]

输出的是地址

![[Pasted image 20251210205543.png]]

相关推荐
落羽的落羽2 小时前
【C++】深入浅出“图”——图的基本概念与存储结构
服务器·开发语言·数据结构·c++·人工智能·机器学习·图搜索算法
bugcome_com2 小时前
C# 中 Overload(重载)与 Override(重写)的核心区别与实战解析
开发语言·c#
凤凰战士芭比Q2 小时前
Jenkins(Pipeline job)
java·servlet·jenkins
巴塞罗那的风2 小时前
从蓝图到执行:智能体中的“战略家思维
开发语言·后端·ai·语言模型·golang
JAVA+C语言2 小时前
Python新手学习
开发语言·python·学习
代码不停2 小时前
BFS解决拓扑排序和FloodFill问题
java·算法·宽度优先
六bring个六2 小时前
文件工具类(一)
开发语言·文件操作工具类
Chengbei112 小时前
CVE-2025-24813 Tomcat 最新 RCE 分析复现
java·安全·web安全·网络安全·tomcat·系统安全·网络攻击模型
AAA简单玩转程序设计2 小时前
救命!Java 进阶居然还在考这些“小儿科”?
java·前端