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 }
  • 相关阅读:
    Item 16: 让const成员函数做到线程安全
    学习张鑫旭大神元素抛物线运动插件
    js根据浏览器对css3移动的支持,选择元素移动方式
    如何在图片加载完成前获取到图片宽高
    JavaScript和SVG实现点击连线
    多层级叠加问题
    闭包应用
    展示触摸屏网页打包成桌面应用(nw.js)
    获取鼠标坐标
    常用文档
  • 原文地址:https://www.cnblogs.com/xiaxj/p/6782948.html
Copyright © 2011-2022 走看看