构造方法及重载

构造器也叫构造方法(constructor),用于对象的初始化。构造器是一个创建对象时被自动调用的特殊方法,目的是对象的初始化。构造器的名称应与类的名称一致。Java通过new关键字来调用构造器,从而返回该类的实例,是一种特殊的方法。

声明格式: 

1

2

3

[修饰符] 类名(形参列表){

    //n条语句

}

要点:

  1. 通过new关键字调用!!

  2. 构造器虽然有返回值,但是不能定义返回值类型(返回值的类型肯定是本类),不能在构造器里使用return返回某个值。

  3. 如果我们没有定义构造器,则编译器会自动定义一个无参的构造函数。如果已定义则编译器不会自动添加!

  4. 构造器的方法名必须和类名一致!

/**
 * 测试构造方法
 * @author Memorial
 *
 */
class Point{
	double x,y;
	
	//构造方法名称和类名必须保持一致
	public Point(double _x,double _y) {
		x=_x;
		y=_y;
	}
Point(){
}
public double getDistance(Point p) {
	return Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.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);
	//Point p2=new Point();
	
	
	System.out.println(p.getDistance(origin));
}
}

输出:
5.0

构造方法的重载(创建不同的用户对象):

/**
 * 构造方法的重载
 * @author Memorial
 *
 */
public class User {
   int id;//id
   String name;//账户名
   String pwd;//密码
public User() {
	  
}
public User(int id,String name) {
	  //super();//构造方法的第一句总是super()
	  this.id=id;//this表示创建好的对象
	  this.name=name;
  }
public User(int id,String name,String pwd) {
	this.id=id;
	this.name=name;
	this.pwd=pwd;
	
}
  public static void main(String[] args) {
	User u1=new User();
	User u2=new User(101,"Memorial");
	User u3=new User(100,"Memorial","123445");
	}
  }
  

如果方法构造中形参名与属性名相同时,需要使用this关键字区分属性与形参。

this.id 表示属性id;id表示形参id

/**
 * 测试this关键字
 * 
 * @author Memorial
 *
 */
public class User1 {
	int id;
	String name;
	String pwd;

	public User1() {

	}

	public User1(int id, String name) {
		System.out.println("正在初始化已经创建好的对象: " + this);
		this.id = id;// 不写this,无法区分局部变量id和成员变量id
		this.name = name;

	}

	public void login() {
		System.out.println(this.name + ",要登录!");// 不写this效果一样

	}

	public static void main(String[] args) {
		User1 u2 = new User1(1010, "Memorial");
		System.out.println("打印Memorial对象:" + u2);
		u2.login();
	}
}

this关键字调用重载构造方法

/**
 * 测试this重载
 * @author Memorial
 *
 */
public class TestThis {
int a,b,c;
TestThis(){
System.out.println("正要初始化一个Hello对象");
}
TestThis(int a,int b){
	//TestThis();//这样是无法调用构造方法的!
	this();//调用无参的构造方法,必须位于第一行
	a=a;//这里都是指的局部变量而不是成员变量
	//这样就区分了成员变量和局部变量。这种情况占了this使用情况大多数!
	this.a=a;
	this.b=b;
	
}
TestThis(int a ,int b,int c){
	this(a,b);//调用带参的构造方法,并且必须位于第一行
	this.c=c;
}
void sing() {
}
void eat() {
	this.sing();//调用本类中的sing();
	System.out.println("快回家吃饭!");
}
public static void main(String[] args) {
	TestThis h=new TestThis(2,3);
	h.eat();
}
}


输出:
正要初始化一个Hello对象
快回家吃饭!

类的构造方法

1.单个构造方法

猜你喜欢

转载自blog.csdn.net/qq_38360675/article/details/85175079