java 构造方法要点整理

java执行系统默认的构造方法时会给所有参数赋值为0或null

如果构建了带参数的构造方法 , 同样要定义<对象名>() , 也就是空参的构造方法 , 否则会产生错误

在同一类下重载构造方法时可以用 : this(<参数>)来替代

public class hello {

	int value;
	String str;
	
	
	public static void main(String[] args) {		
		hello h = new hello(1);
		h.say();
	}
	
	
	public hello(){		//初始化
		this.str = "hello";
		this.value = 0;
	}
	public hello(int value){	//有特定值的 , 进行重载的
		this(value , "hi");
	}
	public hello(int value, String str){       
		this.str = str;
		this.value = value;
	}
	
	
	public void say() {
		System.out.println(this.str);
	}
}

结果为hi

子类继承父类构造方法时
子类继承父类的构造参数并在继承的构造方法中构造这些参数

public class hello {

	public static void main(String[] args) {
		Point3d p3d = new Point3d(1,2,3);
		System.out.println(p3d.x + p3d.y + p3d.z);
	}
}
class Point{
	int x,y;
	Point(int x,int y){
		this.x=x;
		this.y=y;
	}
}
class Point3d extends Point{//x,y,z
	int z;
	Point3d(int x, int y,int z){
		super(x,y);
		this.z=z;
	}
}

结果为6

特别的 , 所有子类的构造方法都会要求引用父类的构造方法也就是super() , 如果父类没有对应的构造方法就会报错

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值