zoukankan      html  css  js  c++  java
  • java this关键字

    在构造方法中实用this

    People.java

    public class People{
        int leg,hand;
        String name;
        People(String s){
            name=s;
            this.init();   //可以省略this,即将this.init();写成init();
        }
        void init(){
           leg=2;
           hand=2;
           System.out.println(name+"有"+hand+"只手"+leg+"条腿");
        }
        public static void main(String args[]){
          People boshi=new People("布什"); //创建boshi时,构造方法中的this就是对象boshi
        }
    } 

    在实例方法中使用this

    class A{
             int x;
             static int y;
             void f(){
                  this.x=100;
                  A.y=200;
             }
    
    }

       上述A类的实例方法f中出现了this,this就代表使用f的当前对象。所以,“this.x”就表示当前对象的变量x,当对象调用方法f时,将100赋给该对象的变量x,因此,当一个对像调用方法时,方法中的实例成员变量就是值分配给该对象的实例成员变量。而static变量和其他对象共享。上述也可以写成

    class A{
             int x;
             static int y;
             void f(){
                  int x;
                  this.x=100;
                  y=200;
             }
    
    }

       但是,当实例成员变量的名字和局部变量的名字相同时,成员变量前面的类名"this"或"类名."就不可以省掉。

  • 相关阅读:
    js模板引擎v5
    js模板引擎v6
    python cookbook学习笔记[一次完成多个字符串的替换]
    您可能没注意到的ie6 select bug
    lambda参数写法问题
    python dict2种遍历方式及区别
    记一次 AXI id debug
    R2B fpga flow script
    axi 1.0
    advanced fpga design
  • 原文地址:https://www.cnblogs.com/yihujiu/p/5990430.html
Copyright © 2011-2022 走看看