day06-封装的优化_构造方法
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
package com.inmind.private02;
|
||||
/*
|
||||
构造方法的使用
|
||||
*/
|
||||
public class Demo04 {
|
||||
public static void main(String[] args) {
|
||||
//无参构造方法,创建学生对象
|
||||
Student s1 = new Student();
|
||||
s1.study("python");
|
||||
//满参构造方法,创建学生对象
|
||||
Student s2 = new Student("张三",18,1);
|
||||
s2.study("java");
|
||||
|
||||
//第一天报名只知道学号
|
||||
Student s3 = new Student(43);
|
||||
System.out.println(s3.getId());
|
||||
s3.study("C++");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,55 @@
|
||||
package com.inmind.private02;
|
||||
/*
|
||||
Student s = new Student();
|
||||
Student():就是Student类的默认无参构造方法,(编译器主动加的!!!)
|
||||
|
||||
普通自定义方法:
|
||||
方法修饰符 返回值类型 方法名(参数列表){
|
||||
return;方法体
|
||||
}
|
||||
|
||||
构造方法:
|
||||
方法修饰符 构造方法名(参数列表){
|
||||
java方法体
|
||||
}
|
||||
|
||||
注意:当源文件(.java文件),进行编译时,编译器扫描整个类的内容,如果没有发现构造方法,那么它会自动帮你添加一个
|
||||
默认无参构造方法,如果你写了构造方法,编译器就不会自动添加默认无参构造方法
|
||||
|
||||
1.构造方法没有返回值类型
|
||||
2.构造方法必须与类名保持一致
|
||||
3.构造方法可以重载(重载:2同1不同)
|
||||
|
||||
构造方法的作用:通过new调用构造方法,创建对象,并且对该对象的属性进行赋值
|
||||
*/
|
||||
public class Student {
|
||||
private String name;
|
||||
private int age;
|
||||
private int id;
|
||||
|
||||
//无参构造方法
|
||||
public Student(){
|
||||
System.out.println("无参构造方法执行了");
|
||||
}
|
||||
//有参构造方法
|
||||
public Student(String name){
|
||||
System.out.println("有参构造方法执行了");
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//有参构造方法
|
||||
public Student(int id){
|
||||
System.out.println("有参构造方法执行了");
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
//满参构造方法,在创建对象的时候,直接对所有属性赋值
|
||||
public Student(String name,int age,int id){
|
||||
System.out.println("满参构造方法执行了");
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
//设置年龄
|
||||
|
||||
Reference in New Issue
Block a user