moocNotes-Java object-oriented programming(this)

package javaObjectOrientedProgrammingMooc;

public class Car {
    private String band;
    private String color;
    Car(){
        band = "Test";
        color = "grey";
    }
    Car(String band, String colorIn){
        band = band;  // ATTENTION 
        color = colorIn;
    }
    public String getBand() {
        return band;
    }
    public String getColor() {
        return color;
    }
}

In line 11, we find that band = band , the left band is a member variable which belong to class Car, the right band is local varaible which belong to function Car(String band, String colorIn).

Maybe you have reliazed that the are same, so, it's hard to distinguish, wo we use this to solve this problem. we use this refer member variable, written as this.band = band.

this have three functions:

  1. this refer member variable in class.

this.member_variable

    public Student(int sno, String sname) {
        this.sno = sno;
        this.sname = sname;
    }
  1. this can call constructor.

    public Student(int sno) {
        this.sno = sno;
    }
    public Student(int sno, String sname) {
        this(sno);
        this.sname = sname;
    }

this(parameter) // Atteneion, no function name between this and ()

  • this调用构造方法,this 调用必须是方法的第一条语句

  • 在构造方法中调用其他构造方法,最多只能调用一次

  • this调用构造方法 不能出现在非构造方法中

  1. this can refer current object.

没太弄明白这个是什么意思

Summary:this 主要在构造方法和非静态的成员方法中使用,主要是引用当前对象的成员或调用当前对象的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值