构造方法
目的:对象初始化,给成员变量赋值。
给成员变量赋值的两种方式:构造方法/setXXX()。
描述:
1.方法名和类名一致
2.通过new关键字调用!
3.构造器有返回值,但不能定义返回值类型(返回值类型是本类)。注意:构造器里可以有return关键字,但只能什么都不返回。如:“return ;”。
4.系统会默认提供无参构造方法,如果有构造方法,不会再提供无参,要用无参需自己给出。
示例
package com.itcode.demo;
/**
* @author: 成都码到功成学员
* @description:
* 构造方法
* 求两个坐标点的距离
*/
class Point{
double a;
double b;
public Point(double _a, double _b) {
a=_a;
b=_b;
}
public double getDistance(Point p) {
return Math.sqrt((a-p.a)*(a-p.a) + (b-p.b)*(b-p.b));
}
}
public class TestConstructor {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 定义两个坐标
Point p1 = new Point(8.0, 6.0);
Point p2 = new Point(0.0, 0.0);
System.out.println(p1.getDistance(p2));
}
}
效果

构造方法重载
示例:
package com.itcode.demo;
/**
* @author: 成都码到功成学员
* @description:
* 构造方法重载
*/
class Teacher{
// 成员属性
int id;
String name;
String work;
// 构造方法是种特殊的重载
// 重载:方法名相同,参数列表不同,与返回值/返回值类型无关
public Teacher() {
}
// 构成重载
public Teacher(int id, String name) {
this.id = id;
this.name = name;
}
// 构成重载
public Teacher(String name, String work) {
this.id = id;
this.name = name;
}
}
public class TestConstructor2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Teacher t1 = new Teacher();
Teacher t2 = new Teacher(02633, "成都码到功成");
Teacher t3 = new Teacher("甄子丹", "成都码到功成当老师");
System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
}
}
雷区
如果方法构造中形参名与属性名相同时,需用this关键字区分属性与形参。this.id 表示属性id,id表示形参id。
Last updated
Was this helpful?