小说网站 搜小说 无限网 烟雨红尘 小说爱好者 免费小说 免费小说网站

《java入门第一季》之面向对象(构造方法)

/*
	构造方法:
		给对象的数据进行初始化

	格式:
		A:方法名与类名相同
		B:没有返回值类型,连void都没有
		C:没有具体的返回值
*/
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();//从这里就有一次调用无参构造的过程。打印输出:   这是构造方法。
		System.out.println(s); //Student@e5bbd6
	}
}


/*
	我们一直在使用构造方法,但是,我们确没有定义构造方法,用的是哪里来的呢?
	
	构造方法的注意事项:
		A:如果我们没有给出构造方法,系统将自动提供一个无参构造方法。
		B:如果我们给出了构造方法,系统将不再提供默认的无参构造方法。
			注意:这个时候,如果我们还想使用无参构造方法,就必须自己给出。建议永远自己给出无参构造方法
		
	给成员变量赋值有两种方式:
		A:setXxx()
		B:构造方法
*/

class Student {
	private String name;
	private int age;
	
	//自己给出构造方法定义
	public Student() {
		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();//null---0
		System.out.println("-------------");
		
		//创建对象2
		Student s2 = new Student("林青霞");//方法重载,自动锁定public Student(String name){},对里面的内容有一次调用
		s2.show();//林青霞---0*//
		System.out.println("-------------");
	
		//创建对象3
		Student s3 = new Student(27);//方法重载,自动锁定public Student(int age){},对里面的内容有一次调用
		s3.show();//null--27
		System.out.println("-------------");
		
		//创建对象4
		Student s4 = new Student("林青霞",27);//传递多个实际参数,自动锁定public Student(String name,int age,String sex){}
		s4.show();//林青霞---27
	}
}




如果您觉得对您有帮助,欢迎写下建议和指正。谢谢。

posted on 2016-05-04 13:20  王小航  阅读(159)  评论(0编辑  收藏  举报

导航