构造器定义: constructor 构造方法
通俗解释:就是在类里边需要定义一个方法名和类名完全相同的的方法,该方法的形参以_开头,如_x。 并将该形参赋值给类属性,如图
class Point {
double x, y;
//构造方法名称和类名必须保持一致
public Point(double _x, double _y) {
x = _x;
y = _y;
}
这样通过new 构造方法名,就可以创建一个该类的、传入特定参数的对象,如图;
Point p = new Point(3.0, 4.0);
Point origin = new Point(0.0, 0.0);
如果想算以上传入的两点的距离,代码如图,体会类的声明,和参数传递
class Point {
double x, y;
//构造方法名称和类名必须保持一致
public Point(double _x, double _y) {
x = _x;
y = _y;
}
public double getDistance(Point m) {
return Math.sqrt((x - m.x) * (x - m.x) + (y - m.y) * (y - m.y));
}
}
public class TestConstructor {
public static void main(String[] args) {
Point p = new Point(3.0, 4.0);
Point origin = new Point(0.0, 0.0);
System.out.println(p.getDistance(origin));
} //此时的origin 是一个Point类型的参数,参数传递给形参m
}
• 构造器是一种特殊的方法:
• 构造器的方法名必须和类名一致!
• 构造器虽然有返回值,但是不能定义返回类型(返回值的类型肯定是本类),不能在构造器里调用
return。
• 通过new关键字调用!!
• 如果我们没有定义构造器,则系统会自动定义一个无参的构造方法。如果已定义,则编译器不会添加无参数构造方法!
• 与普通方法一样,构造方法也可以重载。
构造器的重构:
和普通方法完全一样,要求参数的数量,类型,顺序不同即认为是不同的构造方法,虽然名字相同。
ublic User(int id, String name){this.id = id,参数作用域为就近原则,如果不加this声明,则左,右两边的id都是构造方法中的id,this表示用构造器创建好的对象中的 类属性id
public class User {
int id; // id
public User(int id, String name) {
// super(); //构造方法的第一句总是super()
this.id = id; //this表示创建好的对象。
this.name = name;