关于this的使用

宝塔山上的猫 2015-12-14 06:08:10
public class Rational {
public Rational() {
this(0);
}

public Rational (int n) {
this (n, 1);
}

public Rational(int x, int y) {
int g = gcd(Math.abs(x), Math.abs(y));
num = x / g;
den = Math.abs(y) /g;
if ( y< 0) num = -num;
}

public Rational add(Rational r) {
return new Rational(this.num * r.den + r.num*this.den,
this.den * r.den);
}
public Rational subtract(Rational r) {
return new Rational (this.num * r.den - r.num * this.den, this.den * r.den);
}

public Rational multiply(Rational r) {
return new Rational( this.num * r.num, this.den *r.den);
}

public Rational divide(Rational r) {
return new Rational(this.num * r.den, this.den * r.num);
}

public String toString() {
if (den == 1) {
return "" + num;
}
else {
return num + "/" + den;
}
}

private int gcd(int x, int y) {
int r = x % y;
while (r != 0) {
x = y;
y = r;
r = x % y;
}
return y;
}
private int num;
private int den;
}

我想问一下关于
public Rational add(Rational r) {
return new Rational(this.num * r.den + r.num*this.den,
this.den * r.den);
}中this.num代表的是什么意思?如果可以的话,举个栗子来详细说明它们的参数
...全文
67 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_20062767 2015-12-14
  • 打赏
  • 举报
回复
this关键字有指当前对象的意思,这里的this.num代表的就是当前对象的属性num,而r.den代表的是方法add(Rational r)里面的对象r的属性den,r也是一个Rational 对象,属性num和den都是每个对象一份的,不会相互干扰的,除了特别情况,就是多线程的情况。

50,526

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧