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


    /*
     * 需求:使用java类描述一个动物
     *
     * this关键字注意事项
     *     1:存在同名的成员变量与局部变量时。在方法内部访问的
     *       都是局部变量(java 采取的是就近原则的机制访问的)。
     *     2.如果在一个方法中访问了一个变量,该变量只存在成员变量的情况下
     *       那么java编译器会在该变量的前面添加一个this关键字。
     *  
     * this关键字:
     *    this关键字代表了所属函数的调用者对象。
     *   
     *   
     *   
     * this的作用:
     *    1.如果存在同名的成员变量与局部变量时,在方法内部默认是访问
     *       局部变量的数据,可以通过this关键字指定访问成员变量的数据。
     *    2. 在一个构造函数中可以调用另外一个构造函数初始化对象。
     *
     *
     * this关键字调用其他构造函数的注意事项:
     *     1.this关键字调用其他的构造函数时,this关键字必须位于
     *        构造函数中的第一个语句。
     *     2.this关键字在构造函数中不能出现相互调用的情况,因为是一个
     *        死循环。
     *
     *
     */

    class Animal{
     String name;  // 成员变量
     String color;
     
     public Animal(String n, String c){
      name = n;
      color = c;
     }
     
     
     public void eat()
     {
      //System.out.println("this: " + this);

      
      //String name = "老鼠";  //局部变量

      System.out.println(name + "在吃");
      
     }
    }

    class Demo26
    {
     public static void main(String[] args)
     {
      Animal a = new Animal("狗" , "白色");
      //System.out.println("a: " + a);

      Animal b = new Animal("猫" , "白色");
      b.eat();
      //System.out.println("b: " + b);

     }

    }

    /*

    class Student
    {
     int id;   //成员变量
     String name;
     
     // 存在同名的成员变量与局部变量,在方法内部默认是使用局部变量。
     public Student(int id, String name){   // 一个函数的形式参数也是属于局部变量
      this(name);  // 调用了本类的一个参数的构造方法
      
      this.id = id;   //局部变量的id给成员变量的id赋值
      System.out.println("两个参数的构造方法调用...");
     }
     
     public Student(String name)
     {
      this.name = name;
      System.out.println("一个参数的构造方法调用...");

     }
    }


    class Demo27
    {
     public static void main(String[] args)
     {
      Student s = new Student(110, "二娃");
      
      System.out.println("编号:" + s.id + " 名字:" + s.name);
      //Student s2 = new Student("三娃");

      //System.out.println(" 名字:" + s2.name);
     }
    }

    */

  • 相关阅读:
    Vue项目里添加特殊字体或 某些字体乱码的问题
    Vue 事件修饰符
    js 判断是什么浏览器、是否为谷歌浏览器
    Vue 打印预览功能
    Vue v-if与v-show的区别
    js 下载文件/导出
    使用Mysql Workbench 导入数据库提示 ERROR 1227 (42000) at line 18: Access denied; you need (at least one of) the SUPER privilege(s) for
    java 使用注释校验数据有效性
    java poi分批次导入Excel
    浅谈java中源码常见的几个关键字(native,strictfp,transient,volatile)
  • 原文地址:https://www.cnblogs.com/cpp-cpp/p/6420343.html
Copyright © 2011-2022 走看看