zoukankan      html  css  js  c++  java
  • java _this关键字的用法

    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 }
  • 相关阅读:
    文件参数Python读取wav格式文件
    电子工程术语和定义列表,按字母顺序排列
    MAC地址加减1算法
    uboot通过kernel command line 动态分区 CONFIG_MTD_CMDLINE_PARTS
    c调用shell脚本
    busybox提示can't access tty.job control turned off
    cut命令如何截取以空格隔开的字段
    DS28E01100
    busybox 中的ntpd使用
    Debugfs
  • 原文地址:https://www.cnblogs.com/xiaxj/p/6782948.html
Copyright © 2011-2022 走看看