首页 > 编程语言 > 详细

java _this关键字的用法

时间:2017-04-28 19:51:23      阅读:194      评论:0      收藏:0      [点我收藏+]

1:This关键字可以用于从一个构造方法调用另一个构造方法,可以用于避免重复代码

2:this的第二个用于this.xxx表示成员变量,成员变量的作用范围是  类   避免产生歧义

 1 package com.hone.constructor.testthis;
 2 
 3 public class Animal {
 4     int age=0;
 5     String color="dark color";
 6     
 7     public Animal(int a) {
 8         age=a;
 9         System.out.println("只是初始化年龄:age= "+a);
10     }
11     
12     public Animal(String c) {
13         color=c;
14         System.out.println("只是初始化颜色:color= "+c);
15     }
16     
17     /*
18      * 同时初始化age  color,其中颜色就采用上面的构造方法
19      */
20     public Animal(int a,String c) {
21         //this的用法:从一个构造方法中调用另一个构造方法,
22         this(c);
23         //this的第二个用于this.xxx表示成员变量,成员变量的作用范围是  类
24         this.age=a;
25         System.out.println("同时初始化 age  color");
26     }
27     
28     public Animal() {
29         //这里面利用this的第一个方法:从一个构造方法中调用另一个构造方法
30         this(4, "yellow");
31         System.out.println("默认的构造函数,不含有任何参数");
32     }
33     
34     public void printInfo(){
      this(11);    //如果在该函数中想要给狗的年龄赋值是不允许的,
35 System.out.println("age: "+age+" color: "+color); 36 } 37 38 public static void main(String[] args) { 39 Animal a=new Animal(); 40 a.printInfo(); 41 } 42 43 }

 

java _this关键字的用法

原文:http://www.cnblogs.com/xiaxj/p/6782948.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!