class Point {
protected int x, y;
Point(int a, int b) {
setPoint(a, b);
}
public void setPoint(int a, int b) {
x=a;
y=b;
}
}
这里面的构造函数是如何给成员变量付初值的?就用方法的名字就可以?
为什么不写成:this.a=a;this.b=b;?
protected int x, y;
Point(int a, int b) {
setPoint(a, b);
}
public void setPoint(int a, int b) {
x=a;
y=b;
}
}
这里面的构造函数是如何给成员变量付初值的?就用方法的名字就可以?
为什么不写成:this.a=a;this.b=b;?
在setPoint中的
x = a;
y = b;
就相当于
this.x = a;
this.y = b;
没有二义性的情况下this可以省略.
和下面程序是等同的:
class Point {
protected int x, y;
Point(int a, int b) {
this.x = a;
this.y = b;
}
}
protected int a, b;
Point(int a, int b) {
this.a=a;this.b=b;
}
} 这种方法更常见些
直接这样写不安全,而且复用性低,易读性也差(最好不要直接操作非public属性,而是通过方法
来操作它)
直接这样写不安全,而且复用性低,易读性也差(最好不要直接操作非public属性,而是通过方法
来操作它)这个回答,让我豁然开朗,只是我这段代码写错了
this.x=a;this.y=b;
2.只要new你的构造函数就可以了。
3.this.x ,this.y是调用本类的成员变量 和x,y是等同的。
群号是48603209
大家可以加进去相互交流下。
形参和实参没同名的时候用不着加this
一般来讲,你如果在构造函数中想操作private类型变量也行,不过最好使用transient关键字。
参考JDK源码:(Date类)
public class Date
implements java.io.Serializable, Cloneable, Comparable<Date>
{
private transient long fastTime;
/**
* Allocates a <code>Date</code> object and initializes it to
* represent the specified number of milliseconds since the
* standard base time known as "the epoch", namely January 1,
* 1970, 00:00:00 GMT.
*
* @param date the milliseconds since January 1, 1970, 00:00:00 GMT.
* @see java.lang.System#currentTimeMillis()
*/
public Date(long date) {
fastTime = date;
}
}
如果参数多个的话,一般都采用此写法,this.a=a,你看过hibernate的po写法吗,一般构造都是这种写法的。