Java 基础(3) —— this 的用法
来源:互联网 发布:服务器 定时关机 软件 编辑:程序博客网 时间:2024/06/06 05:56
用途1:在类里面来引用这个类的属性
this
对象,它可以在类里面来引用这个类的属性和方法。
this 关键字
是类内部当中对自己的一个引用,可以方便类中方法访问自己的属性
public class thisDemo_1 { String name = "Mick"; public void print(String name) { // this 对象,它可以在类里面来引用这个类的属性和方法 System.out.println("类中的属性 this.name = " + this.name); System.out.println("局部传参的属性 name = " + name); } public static void main(String[] args) { thisDemo_1 tt = new thisDemo_1(); tt.print("Orson"); }}
类中的属性 this.name = Mick局部传参的属性 name = Orson
用途2:在一个构造函数中,通过this来调用另一个构造函数
一个类中定义两个构造函数,在一个构造函数中通过 this 来调用另一个构造函数
在无参数构造方法中调用有参数构造方法
public class Dog { private String name; private int age; // 有参数的构造方法 public Dog(String name, int age) { this.name = name; this.age = age; System.out.println("this.name = " + this.name); System.out.println("this.age = " + this.age); } // 这个无参构造方法里调用的有参数的构造方法,这个也就是this的第二种用法了! public Dog() { this("nihao", 20); } public static void main(String[] args) { System.out.println("【有参数】的构造方法测试如下:"); Dog has_args = new Dog("Mike", 17); System.out.println("【无参数】的构造方法测试如下:"); Dog no_args = new Dog(); }}
【有参数】的构造方法测试如下:this.name = Mikethis.age = 17【无参数】的构造方法测试如下:this.name = nihaothis.age = 20
在有参数构造方法中调用无参数构造方法
public class ThisDemo_3 { String name; int age; public ThisDemo_3() { this.age = 21; } public ThisDemo_3(String name, int age) { this(); this.name = "Mick"; } private void print() { System.out.println("最终名字=" + this.name); System.out.println("最终的年龄=" + this.age); } public static void main(String[] args) { ThisDemo_3 tt = new ThisDemo_3("Mick", 0); // 随便传进去的参数 tt.print(); }}
最终名字=Mick最终的年龄=21
用途3:通过 this 返回自身这个对象
通过
this 关键字
返回自身这个对象然后在一条语句里面实现多次的操作
public class ThisDemo_2 { int number = 0; ThisDemo_2 increment() { number++; return this; } private void print() { System.out.println("number=" + number); } public static void main(String[] args) { ThisDemo_2 tt = new ThisDemo_2(); tt.increment().increment().increment().print(); System.exit(0); }}
number=3
阅读全文
0 0
- Java 基础(3) —— this 的用法
- Java 基础——This 用法
- Java 基础——This 用法
- 黑马程序员:Java基础总结----this的用法(super)
- Java基础之(四) this的用法
- Java-面向对象(基础篇)--this关键字的用法
- Java基础:this和super的用法
- Java基础——super的几种用法并与this的区别
- java基础学习总结——super的几种用法并与this的区别
- Java基础之This用法
- Java 基础【01】 This 用法
- Java 基础【01】 This 用法
- Java基础【01】this用法
- Java 基础【01】 This 用法
- Java 基础【01】 This 用法
- JAVA的this用法
- Java - this的用法
- java This的用法
- 数据结构——链表之有序链表的建立
- matlab中图像叠加
- aspx文件,app_code内的类无法使用的排查 编译器错误消息 CS0246 找不到类型或命名空间名称“QPUtils”(是否缺少 using 指令或程序集引用)
- java客户端访问集群时用户权限报错:rg.apache.hadoop.security.AccessControlException:
- Python 窗体(tkinter)列表框(Listbox)
- Java 基础(3) —— this 的用法
- linux网络API细节
- makefile
- Ajax-combobox动态绑定数据
- Modbus协议学习(四)
- UVA 11082 Matrix Decompressing——抽象建图+最大流
- 英语学习记录
- 【Spring】手动实现AOP编程(十一)
- 金额转换