java中this的用法

1) 调用对象自己
  1. public class Leaf {
  2.     private int i = 0;
  3.     Leaf increment() {
  4.         i++;
  5.         return this;
  6.     }
  7.     void print() {
  8.         System.out.println("i = " + i);
  9.     }
  10.     public static void main(String[] args) {
  11.         Leaf x = new Leaf();
  12.         x.increment().increment().increment().print();
  13.     }
  14. }
2) 一个构造函数调用另一个构造函数,必须是第一条语句,并且不能调用两个以上的的构造函数。
  1. public class Flower {
  2.     private int petalCount = 0;
  3.     private String s = new String("null");
  4.     
  5.     Flower(int petals) {
  6.         petalCount = petals;
  7.         System.out.println("Constructor w/ int arg only, petalCount= "+ petalCount);
  8.     }
  9.     
  10.     Flower(String ss) {
  11.         System.out.println("Constructor w/ String arg only, s=" + ss);
  12.         s = ss;
  13.     }
  14.     
  15.     Flower(String s,int petals) {
  16.         this(petals);
  17.         //! this(s); // Can't call two!
  18.         this.s = s; // Another use of "this"
  19.         System.out.println("String & int args");
  20.     }
  21.     
  22.     Flower() {
  23.         this("hi"47);
  24.         System.out.println("default constructor (no args)");
  25.     }
  26.     void print() {
  27.         //! this(11); // Not inside non-constructor!
  28.         System.out.println("petalCount = " + petalCount + " s = " + s);
  29.     }
  30.     public static void main(String[] args) {
  31.         Flower x = new Flower();
  32.         x.print();
  33.     }
  34. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值