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

    this:代表当前对象

    this.属性;  操作当前对象的属性

    this.方法();  调用当前对象的方法

    封装对象的属性的时候,尝使用this关键字

    class Telphone{

    private float screen;    //若将“private”改为“public”,

    private float cpu;

    private float mem;

    public void sendMessage(){

    System.out.println("sendMessage");

    }

    public float getScreen(){

    return screen;

    }

    public float setScreen(float screen){    //若将“public”改为“private”,则该方法只能在类的内部使用

    this.screen=screen;    //为了区分属性和参数名,所以在参数名前+this,意思为:将参数的值赋给当前对象的属性

    this.sendMessage();    //调用当前对象的方法

    }

    public float getCpu(){

    return cpu;

    }

    public void setCpu(float cpu){

    this.cpu=cpu;

    }

    public float getMem(){

    return mem;

    }

    public void setMem(float mem){

    this.mem=mem;

    }

    public Telphone(){

    System.out.println("无参的构造方法执行了");

    }

    public Telphone(float newScreen,float newCpu,float newMem){

    if(newScreen<3.5f){

    System.out.println("输入的数据错误");

    screen=3.5f;

    }

    cpu=newCpu;

    mem=newMem;

    System.out.println("有参的构造方法执行了");

    }

    }

    class Ex17{

    public static void main(String[] args){

    Telphone phone2=new Telphone(1.5f,1.4f,2.0f);

    //若将“private”改为“public”,则在此添加 “phone2.screen=6.0f;” 不会报错

    System.out.println("screen:"+phone2.getScreen());

    }

    }

    this的使用

    1.在方法和构造方法中,使用this来访问字段及方法

    如,方法sayHello中使用this.name是相同的。即:

    void sayHello{

    System.out.println("Hello!My name is "+name);

    }

    void sayHello{

    System.out.println("Hello!My name is "+this.name);

    }

    的含义相同

    2.使用this解决局部变量与域同名的问题  /*域就是范围的意思
                        例{}之间,称为一块域,用来描述变量适用范围,全局变量的域是整个类,局部变量只适用于他所在的{}之间*/

    使用this还可以解决局部变量(方法中的变量)或参数变量与域变量同名的问题。

    如:Person(int age,String name){

    this.age=age;

    this.name=name;

    }

    这里,this.age表示域变量,age表示参数变量

    通过this关键字可明确访问一个类的成员变量

    class Person{

      int age;

       public Person(int age){

        this.age=age;

      }

       public int getAge(){

        return (this.)age;

      }

    }

    在构造方法中,this.age是访问成员变量,age是访问局部变量

    3.构造方法中,用this调用另一构造方法

    构造方法中,还可用this来调用另一构造方法。如:

    Person(){

    this(0,"");

    .......

    }

    在构造方法中调用另一构造方法,则这条调用语句必须放在第一句

  • 相关阅读:
    第十四周 Leetcode 315. Count of Smaller Numbers After Self(HARD) 主席树
    POJ1050 To the Max 最大子矩阵
    POJ1259 The Picnic 最大空凸包问题 DP
    POJ 3734 Blocks 矩阵递推
    POJ2686 Traveling by Stagecoach 状态压缩DP
    iOS上架ipa上传问题那些事
    深入浅出iOS事件机制
    iOS如何跳到系统设置里的各种设置界面
    坑爹的私有API
    业务层网络请求封装
  • 原文地址:https://www.cnblogs.com/chenyuan7/p/7913334.html
Copyright © 2011-2022 走看看