zoukankan      html  css  js  c++  java
  • java中的this

    this的使用场景

           1、调用这个函数的对象

       2、用类的成员变量,而不是函数的参数。主要是对同名的函数参数和成员变量进行区分。局部变量与成员变量同名的时候,成员变量会被屏蔽,this.成员变量可以用来引用成员变量。

       3、在构造方法中引用满足指定参数类型的构造方法,注意只能引用一个构造方法且位于开始。

     1 public class Student{
     2      String name;
     3      String sex;
     4      int age;
     5      Student(String name){//第一个构造函数
     6             this.name = name;//第二种this的使用
     7      }
     8      Student(String name,String sex,int age){//第二个构造函数
     9             this(name);     //第三种this的使用
    10             this.sex = sex;
    11             this.age = age;
    12      }
    13      void display(){
    14      System.out.println("name=" + this.name);
    15      System.out.println("sex=" + this.sex);
    16      System.out.println("age=" + this.age);//this引用该类的成员变量
    17 18      public Student increment(){
    19             this.sex = "不明";
    20             this.age = 0;
    21             return this;//第一种this的使用,返回当前对象
    22      }
    23      public static void main(String[] args) {
    24             Student zhangsan = new Student("张三", "男", 19);
    25             zhangsan.display();
    26             Student lisi = new Student("李四");
    27             System.out.println(lisi.increment.sex);
    28       }
    29 }

    输出的结果为:

    name = 张三
    sex = 男
    age = 19
    不明
    

    需要格外注意的是:this不能用在static方法中

    关于static方法不能使用this的简单理解

             this只能用于方法方法体内,当一个对象创建后,Java虚拟机(JVM)就会给这个对象分配一个this用来引用自身。因此,this只能在类中的非静态方法中使用,静态方法和静态的代码块中绝对不能出现this。静态方法和静态数据成员会随着类的定义而被分配和装载入内存中;非静态方法和非静态数据成员只有在类的对象创建时在对象的内存中才有这个方法的代码段;如果静态引用了非静态的,根本无法从内存中找到非静态的代码段,势必会出错。

  • 相关阅读:
    团队冲刺八
    第十一周学习进度
    团队冲刺七
    团队冲刺六
    团队冲刺五
    冲刺第五天
    冲刺第四天
    冲刺第三天
    冲刺第二天
    冲刺第一天
  • 原文地址:https://www.cnblogs.com/541wsy/p/12497564.html
Copyright © 2011-2022 走看看