day06--封装的优化_构造方法
This commit is contained in:
@@ -0,0 +1,15 @@
|
|||||||
|
package com.inmind.constructor03;
|
||||||
|
|
||||||
|
public class Demo04 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//创建学生
|
||||||
|
Student s = new Student();
|
||||||
|
System.out.println(s.name);
|
||||||
|
//直接创建学生并携带name属性
|
||||||
|
Student s1 = new Student("张三");
|
||||||
|
System.out.println(s1.name );
|
||||||
|
Student s2 = new Student("李四",18);
|
||||||
|
System.out.println(s2.name);
|
||||||
|
System.out.println(s2.age);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package com.inmind.constructor03;
|
||||||
|
/*
|
||||||
|
Student():就是学生类的默认无参构造方法
|
||||||
|
|
||||||
|
普通自定义方法:
|
||||||
|
方法修饰符 返回值类型 方法名(参数列表){
|
||||||
|
return;方法体
|
||||||
|
}
|
||||||
|
|
||||||
|
构造方法:
|
||||||
|
方法修饰符 构造方法名(参数列表){
|
||||||
|
java方法体
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
注意:当源文件(.java文件),进行编译时,编译器扫描整个类的内容,如果没有发现构造方法,那么它会自动帮你添加一个
|
||||||
|
默认无参构造方法,如果你写了构造方法,编译器就不会自动添加默认无参构造方法
|
||||||
|
|
||||||
|
1.构造方法没有返回值类型
|
||||||
|
2.构造方法必须与类名保持一致
|
||||||
|
3.构造方法可以重载
|
||||||
|
|
||||||
|
构造方法的作用:通过new调用构造方法,创建对象,并且对该对象的属性进行赋值
|
||||||
|
*/
|
||||||
|
public class Student {
|
||||||
|
//成员变量
|
||||||
|
String name;
|
||||||
|
int age;
|
||||||
|
|
||||||
|
//构造方法
|
||||||
|
//无参构造方法
|
||||||
|
public Student(){
|
||||||
|
System.out.println("学生类的无参构造方法执行了");
|
||||||
|
}
|
||||||
|
|
||||||
|
//有参构造
|
||||||
|
public Student(String name){
|
||||||
|
this.name = name;
|
||||||
|
System.out.println("学生类的有参构造方法执行了");
|
||||||
|
}
|
||||||
|
|
||||||
|
//满参构造&全参构造
|
||||||
|
public Student(String name,int age){
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
System.out.println("学生类的满参构造方法执行了");
|
||||||
|
}
|
||||||
|
|
||||||
|
//成员方法
|
||||||
|
public void study(){
|
||||||
|
System.out.println("学生学习");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user