为什么我们在setter方法中使用'this'而不在getter方法中使用? [英] Why do we use 'this' in setter method but not in getter method?

查看:147
本文介绍了为什么我们在setter方法中使用'this'而不在getter方法中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在以下代码中:

private int id;

public void setID(int ID) {
    this.id = ID;
}

public void getID() {
    return id;
}

我们为什么不在getter函数中说return this.id或相反在setter函数中说id = ID?还有this实际必要吗?我的意思是,不是通过对象(例如obj.setid(1)obj.getid())调用函数吗?如果我不使用this关键字,它会以不同的方式工作吗?

Why don't we say return this.id in the getter function or conversely say id = ID in the setter function? Also is this actually necessary? I mean, aren't the functions called through an object, say obj.setid(1) or obj.getid()? Will it work differently if I don't use the this keyword?

推荐答案

当变量名相同时,您需要使用this.是要区分它们.

You need to use this when the variable names are the same. It is to distinguish between them.

public void setID(int id) {
    this.id = id;
}

当删除this时,以下内容仍将起作用.这是因为它们的名称不同.

The following will still work when this is removed. It is because their names are not the same.

public void setID(int ID) {
    id = ID;
}

这篇关于为什么我们在setter方法中使用'this'而不在getter方法中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆