-- rem 关键字 rgs java err style ret 基础总结
在java中, this 对象,它可以在类里面来引用这个类的属性和方法。
1.它在方法内部使用,即这个方法所属的对象的引用。
2.它在构造器内部使用,表示该构造器正在初始化的对象。
3.this表示当前对象,可以调用类的属性、方法和构造器。
在方法内需要用到调用该方法的对象是,就用this。
- public class ThisDemo {
- int num;
- ThisDemo increment() {
- num++;
- return this;
- }
- private void print() {
- System.err.println("num=" + num);
- }
- public static void main(String[] args) {
- ThisDemo tt = new ThisDemo();
- tt.increment().increment().increment().print();
- }
- }
通过this 这个关键字返回自身这个对象然后在一条语句里面实现多次的操作。
使用this调用本类的构造器
- public class ThisDemo2 {
- String name;
- int age;
- public ThisDemo2() {
- this.age = 21;
- }
- public ThisDemo2(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) {
- ThisDemo2 tt = new ThisDemo2("", 0); //随便传进去的参数
- tt.print();
- }
- }
java基础总结(二)---关键字
-- rem 关键字 rgs java err style ret 基础总结
原文:http://www.cnblogs.com/codeRose/p/7679148.html
来源: http://www.bubuko.com/infodetail-2384365.html