Java构造方法与构造方法重载

1.构造方法

构造器也叫构造方法(constructor),用于对象的初始化。Java通过new关键字来调用构造器,从而返回该类的实例

声明格式:

[修饰符]类名(形参列表){
	//n条语句
}

构造器4个要点:

  • 构造器通过new关键字调用

  • 构造器虽然有返回值,但是不能定义返回值类型,不能在构造器里使用return返回某个值

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

  • 构造器的方法名必须和类名一致

举例

class Point{
	double x;
	double y;
	public Point(double _x,double _y) {
		this.x = _x;
		this.y = _y;
	}
	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 orgin = new Point(0.0,0.0);
		System.out.println(p.getDistance(orgin));
		
		
	}
}

2.构造方法重载

public class User {
	int id;
	String name;
	String pwd; //密码
	public User() {
		
	}
	public User(int id,String name) {
		this.id = id;
		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,"fei");
		User u3 = new User(102,"fei","123456");
	}
	
}

重载就是方法名相同,形参不同,通过方法名+形参列表一起调用的方式进行。

通过this表示属性和形参。

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值