案例代码
public class Car {
String color;
int speed;
int seat = 5;
public void run(){
System.out.println("车能跑");
System.out.println(this.color);
System.out.println(this.seat);
}
public static void main(String[] args) {
Car c = new Car();
c.color = "红色";
c.speed = 130;
c.run();//在调用方法的时候,java会自动把对象传递给方法,在方法中
//有this来接受对象
}
}
小结
this 可以在方法体内部对参数进行调用,与Python里的self.变量名,的用法类似。
本文通过一个简单的Java案例,介绍了this关键字的基本用法及其在方法体内的作用。this关键字可以用来引用当前对象的属性,类似于Python中的self.变量名。文章通过一个Car类的实例展示了如何在方法中使用this。
3596

被折叠的 条评论
为什么被折叠?



