java中的this
2016-02-11 22:55
429 查看
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作为返回值,则可以多次连续调用一个方法: ```java public 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 */
相关文章推荐
- java常见问题
- Java—设计模式(工厂模式)
- 栈的应用--四则运算表达式求值(java代码)
- JAVA比较两个日期相差的天数
- Arcgis server java develop begining
- Gradle教程Part2:java工程
- Java开发环境搭建
- java基础总结 --- enum枚举实现多路分发 石头、剪刀、布游戏示例
- The Java™ Tutorials — Concurrency :Memory Consistency Errors 内存一致性错误
- Spark学习笔记7-在eclipse里用scala编写spark程序(单机和集群运行)
- JDK中自带xml和对象互转方法
- 蓝桥杯 算法训练 最小乘积(基本型)
- JAVA常见基本术语
- java synchronized详解(转载)
- Java多线程ExecutorService.shutdown什么时候执行
- 总结-Java何时需要使用多线程
- 20个非常有用的Java程序片段
- 蓝桥杯 算法训练 图形显示
- [Spring实战系列](16)面向切面编程(AOP)概述
- Java多线程通过多核CPU来提升速度--更快的执行