目录
this关键字
# 引用
代码如下
public class Student {
=======
修子的日记 目录
this关键字
# 引用
代码如下
public class Student {
>>>>>>> 593e4ea (添加了SSM)
String name;
int age;
boolean sex;
String address;
}
int i = 10; // 测试用
Student s = new Student();
s是引用,在栈内存(主栈的栈内存),指向学生对象,学生对象在堆内存
# this关键字
# this 是什么?
一句话,this 是位于堆内存的引用(复习:引用是保存地址的变量),保存的内存地址是自身对象,很像日常用语的物主代词
详细点说:
- this 存储在 JVM 堆内存 实例对象内部。
- 一百个对象有 100 个内存,有 100 个不同的 this。this 变量中保存了自身内存地址,也就是指向自身
# 例子
public class Customer {
String name;
public Customer(){
// 无参数的构造函数
}
public void shopping(){
System.out.println(this.name + "正在购物");
}
}
这里 this.name
张三用是张三,李四用是李四
配合属性,和日常会话中的物主代词 his/her 很像

当使用 c1 去访问该对象的话,整个过程中出现的 this 就是 c1
当使用 c2 去访问该对象的话,整个过程中出现的 this 就是 c2
# 和 python self 的区别
“self”不是关键字,而“this”是关键字
从技术上讲,self 和 this 作用都是:访问与当前实例关联的变量。唯一的区别是,您必须明确地将 self 作为第一个参数包含在 Python 中的实例方法中,而 Java 则不是这种情况。此外,名称 self 可以是任何名称。如您所知,它不是关键字。您甚至可以将其更改为 this,它会正常工作。但是人们喜欢使用 self,因为它现在已经成为一种约定。
这是一个在 Python 和 Java 中访问实例变量的简单实例方法:
Python:
class Circle(object):
def __init__(self, radius):
# declare and initialize an instance variable
self.radius = radius
# Create object. Notice how you are passing only a single argument.
# The object reference is implicitly bound to `self` parameter of `__init__` method
circle1 = Circle(5);
Java:
class Circle {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
}
Circle circle1 = new Circle(5);
- 跟随系统
- 浅色模式
- 深色模式
- 阅读模式