部分学校先学习了C++,知道在一个类中的构造函数可以调用另一个。
例如:
class exampleclass
{
public:
exampleclass(int i, int p)
{
this->i = i;
this->p = p;
}
exampleclass(int i):exampleclass(i, i* i){}
private:
int i;
int p;
};
比如在这里第10行的构造函数调用了第4行的构造函数。
当学校再学JAVA时便不知如何构造类了,其实很简单只是语法不同。
public class Point {
float X;
float Y;
int type;
public Point(float X, Float Y)
{
this.X = X;
this.Y = Y;
this.type = -1;
}
public Point(Point yourPoint)
{
this.X = yourPoint.X;
this.Y = yourPoint.Y;
this.type = yourPoint.type;
}
public Point(Point youPointIgonreID, int ID)//调用已有的方法
{
this(youPointIgonreID);//使用this调用
this.type = ID;
}
第20行的函数便是调用已有的构造方法。方法很简单就是使用“this”即可。