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

    三个特点:调用本类属性,调用本类方法(普通和构造),表示当前对象(最难理解的概念)

    1.使用this调用本类属性

    观察如下代码

    class Person{

      private string name ;

      private int age 

      // setter  getter 无参构造略

      public  Person(String name,int age)

      {   // this.属性,当前对象中的属性

        this.name = n;

        this.age = a;

      }

      public string getInfo()

      {  

        return "姓名:" + this.name + ",年龄:" + this.age ;

      }

    }

    public class Thisdemo{

      public static void main(String args[])

      {  

        System.out.println(new Person("张三:",20).getInfo());

      }

    }

    2.this 调用方法(普通和构造)

    普通方法:this.方法名称(参数...)

    构造方法:this(参数)

    本类方法和构造方法的区别:使用关键字new实例化类新对象的时候使用一次,而普通方法是在实例化完成了(构造已经执行过了)可以调用多次,在java里面支持类构造方法的相互调用(并且要放在第一行) 使用this调用构造方法的时候请留有出口(防止递归构造调用)。

    3.this表示当前对象

    在一个类之中会产生若干个对象,程序类在分辨的时候不会记住具体有多少个类,只会知道操作本类的对象是哪一个

    范例:观察当前对象

    class Person

    {

      public void fun()

      {

        System.out.println("fun()方法" + this);

      }

    }

    public class Thisdemo{

      public static void main(String args[])

      {

        Person p1 = new Person();

        System.out.println("man方法" + p1);

        p1.fun();  // 由p1这个对象调用了fun()方法

        System.out.println("===============");

        Person p2 = new Person();

        System.out.println("man方法" + p2);

        p2.fun(); 

      }

    }

  • 相关阅读:
    【操作系统】用Oracle VM VirtualBox 虚拟机安装XP系统时老是蓝屏
    c#操作Xml(六)
    c#操作Xml(五)
    c#操作Xml(三)
    c#操作Xml(四)
    新年快乐
    c#操作Xml(八)
    从IDataReader中读取数据实体
    c#操作Xml(七)
    c#操作Xml(二)
  • 原文地址:https://www.cnblogs.com/123talents/p/7467465.html
Copyright © 2011-2022 走看看