java_面向对象_构造方法_7

  • 构造方法的及其特点:
    构造方法是为了给对象的数据进行初始化。
1. 方法名与类名相同
2. 没有返回值类型。 //连void也没有。
3. 没有具体的返回值。

我们一直在使用构造方法,但是,我们确没有定义构造方法。

A:如果我们没有给出构造方法,系统将自动提供一个无参构造方法。
B:如果我们给出了构造方法,系统将不再提供默认的无参构造方法。

注意:这个时候,如果我们还想使用无参构造方法,就必须自己给出。
建议永远自己给出无参构造方法
  • 给成员变量赋值有两种方式:
	A:setXxx()
	B:构造方法
  • jdk提供的默认构造方法
    在这里插入图片描述
  • 自己给出无参构造方法
    在这里插入图片描述
  • 自己给出有参构造方法
    在这里插入图片描述
  • 多个构造方法并存
    在这里插入图片描述
  • 代码解释
class Student {
	private String name; //null
	private int age; //0
	
	public Student() {
		System.out.println("这是无参构造方法");
		//构造方法在类创建对象的时候运行,用来给对象的数据进行初始化。
	}
}

class ConstructDemo {
	public static void main(String[] args) {
		Student s = new Student();  //带括号的都是方法,Student()是无参构造方法。
		//创建了一个对象s,并且这个同时运行了构造方法。
		System.out.println(s); //Student@e5bbd6
	}
}
class Student {
	private String name;
	private int age;

	public Student() {
		//System.out.println("我给了,你还给不");
		System.out.println("这是无参构造方法");
	}
	
	//构造方法的重载格式
	public Student(String name) {
		System.out.println("这是带一个String类型的构造方法");
		this.name = name;
	}
	
	public Student(int age) {
		System.out.println("这是带一个int类型的构造方法");
		this.age = age;
	}
	
	public Student(String name,int age) {
		System.out.println("这是一个带多个参数的构造方法");
		this.name = name;
		this.age = age;
	}
	
	public void show() {
		System.out.println(name+"---"+age);
	}
}

class ConstructDemo2 {
	public static void main(String[] args) {
		//创建对象
		Student s = new Student();
		s.show();
		System.out.println("-------------");
		
		//创建对象2
		Student s2 = new Student("林青霞");
		s2.show();
		System.out.println("-------------");
		
		//创建对象3
		Student s3 = new Student(27);
		s3.show();
		System.out.println("-------------");
		
		//创建对象4
		Student s4 = new Student("林青霞",27);
		s4.show();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值