Javathis关键字详解

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Javathis关键字详解
this 关键字⽤来表⽰当前对象本⾝,或当前类的⼀个实例,通过this可以调⽤对象的所有⽅法和属性。

1public class Demo {
2private int x = 10;
3private int y = 15;
4
5public void sum(){
6//通过this获取成员变量,this可以省略。

7int z = this.x + this.y;
8 System.out.println("x+y = "+z);
9 }
10
11public static void main(String[] args) {
12 Demo demo = new Demo();
13 demo.sum();
14 }
15 }
使⽤this区分同名变量
1public class Demo {
2private String name;
3private int age;
4
5public Demo(String name,int age){
6//this不能省略, 指的是成员变量,等于后⾯的name 是传⼊参数的变量,this可以很好的区分两个变量名⼀样的情况。

= name;
8this.age = age;
9 }
10public static void main(String[] args){
11 Demo demo = new Demo("微学院",3);
12 System.out.println( + "的年龄是" + demo.age);
13 }
14 }
使⽤this作为⽅法名来实例化对象
1public class Demo {
2private String name;
3private int age;
4
5public Demo(){
6/**
7 * 构造⽅法中调⽤另⼀个构造⽅法,调⽤动作必须置于最起始位置。

8 * 不能在构造⽅法之外调⽤构造⽅法。

9 * ⼀个构造⽅法只能调⽤⼀个构造⽅法。

10*/
11this("微学院",3);
12 }
13
14public Demo(String name,int age){
= name;
16this.age = age;
17 }
18
19public static void main(String[] args){
20 Demo demo = new Demo();
21 System.out.println( + "的年龄是" + demo.age);
22 }
23 }
this作为参数传递
1class Person{
2public void eat(Apple apple){
3 Apple peeled = apple.getPeeled();
4 System.out.println("Yummy");
5 }
6 }
7class Peeler{
8static Apple peel(Apple apple){
9return apple;
10 }
11 }
12class Apple{
13 Apple getPeeled(){
14//传⼊this,就是传⼊Apple。

15return Peeler.peel(this);
16 }
17 }
18public class This{
19public static void main(String args[]){ 20new Person().eat(new Apple());
21 }
22 }。

相关文档
最新文档