java中的this
来源:互联网 发布:局域网演示软件 编辑:程序博客网 时间:2024/06/08 04:16
java中的this
this主要要三种用法:
1、表示对当前对象的引用。
2、表示用类的成员变量(而非函数参数)。
3、用于在构造方法中引用满足指定参数类型的构造方法。
注意:this不能用在static方法中。每当一个对象创建后,Java虚拟机会给这个对象分配一个引用自身的指针,这个指针的名字就是 this。因此,this只能在类中的非静态方法中使用,静态方法和静态的代码块中绝对不能出现this的用法。
这里this表示什么?
// 该例意在演示this的用法public class MyDate { private int day, month, year; // 创建构造方法 public MyDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public String tommorrow() { day = day +1; return day + "/" + month + "/" + year; } public static void main(String[] args) { MyDate d = new MyDate(11,2,2016); System.out.println(d.tommorrow()); }}/* * 12/2/2016 * */ ```如果在某个方法中把this作为返回值,则可以多次连续调用一个方法:```javapublic class ReturnThis { int number; ReturnThis increment() { number++; return this; } private void print() { System.out.println("number = " + number); } public static void main(String[] args) { ReturnThis tt = new ReturnThis(); tt.increment().increment().increment().increment().print(); }}<div class="se-preview-section-delimiter"></div>
体会下面的两个例子:
public class ThisDemo { String name; int age; public ThisDemo() { this.age = 21; } public ThisDemo(String name, int age) { //this(); this.name = "Nick"; } private void print() { System.out.println("最终的名字 = " + this.name); System.out.println("最终的年龄 = " + this.age); } public static void main(String[] args) { ThisDemo tt = new ThisDemo("", 0); // 随便传进去的参数 tt.print(); }}/* * 最终的名字 = Nick最终的年龄 = 0 */<div class="se-preview-section-delimiter"></div>
public class ThisDemo { String name; int age; public ThisDemo() { this.age = 21; } public ThisDemo(String name, int age) { this(); this.name = "Nick"; } private void print() { System.out.println("最终的名字 = " + this.name); System.out.println("最终的年龄 = " + this.age); } public static void main(String[] args) { ThisDemo tt = new ThisDemo("", 0); // 随便传进去的参数 tt.print(); }}/* * 最终的名字 = Nick最终的年龄 = 21 */
0 0
- 【Java】java中的this
- java 中的this变量
- java中的this用法
- java中的this关键字
- java 中的this关键字
- java中的this关键字
- Java中的 this使用
- java中的this关键字
- java中的关键字this
- java 中的关键字 this
- Java中的this关键字
- Java中的this
- java中的THIS指针
- Java中的this
- java中的this
- Java中的this指针
- Java中的this关键字
- Java 中的this深解
- 面试笔试杂项积累-leetcode 216-220
- django signal and contenttypes初探,可用于好友最新动态,新鲜事,消息通知等
- Oracle第学习四天
- KVO(键值监听)详解
- 实现Socket服务端监听(模拟10086在线服务)
- java中的this
- bzoj1005: [HNOI2008]明明的烦恼
- Atitit.跨语言反射api 兼容性提升与增强 java c#。Net php js
- Atitit.变量的定义 获取 储存 物理结构 基本类型简化 隐式转换 类型推导 与底层原理 attilaxDSL
- VS2015中cout、cin未声明的标识符错误的处理
- ytr920609ytr
- HDU 2126(01背包扩展,记录方案数)
- java中的构造方法
- 112. Path Sum LeetCode