搜索文档
知识点
- 在代码中,通过 new 关键字调用一个类的构造方法,也就是创建对象时会执行类的构造方法。
- 构造方法的方法名必须与类名一致。
- 构造方法虽然有返回值,但是在定义构造方法时不能定义方法的返回值类型,在方法内部也不能使用 return 返回某个值。
- 如果我们没有定义构造方法,则编译器会自动定义一个无参的构造方法,方便我们 new 一个类的实例对象。
代码实现
需求
- 定义一个 “点” 类。
- 属性包括:横坐标 x,纵坐标 y
- 方法包括:构造方法,计算两点距离方法。
代码
java
public class Index {
public static void main(String[] args) {
Point p1 = new Point(3,4);
Point p2 = new Point(0,0);
double distance = p2.computeDistance(p1);
System.out.println(distance);
}
}
class Point {
double x,y;
// 定义构造方法
public Point(double _x,double _y) {
x = _x;
y = _y;
}
/*
* 根据勾股定理计算两点间距离
* Math.sqrt(n): 开平方函数
* Math.pow(i,j):计算 i 的 j 次方
*/
public double computeDistance(Point p) {
return Math.sqrt(Math.pow((p.x - x),2) + Math.pow((p.y - y),2));
}
}
构造方法的重载
构造方法的重载和 普通方法的重载 是一样的。
构造方法的参数个数不同、参数类型不同、参数位置不同都会引起方法重载。
代码演示
javapublic class Index { public static void main(String[] args) { Student stu1 = new Student(1001); Student stu2 = new Student(1002,"张三"); Student stu3 = new Student("李四",1003); System.out.printf("ID:%s\n",stu1.id); System.out.printf("ID:%s,name:%s\n",stu2.id,stu2.name); System.out.printf("ID:%s,name:%s\n",stu3.id,stu3.name); } } class Student { int id; String name; int age; public Student(int id) { this.id = id; } public Student(int id,String name) { this.id = id; this.name = name; } public Student(String name,int id) { this.id = id; this.name = name; } }
快速生成
command + N
选择 Constructor

