day06-面向对象特性之封装的优化_构造方法
This commit is contained in:
16
day06/src/com/inmind/constructor03/Demo05.java
Normal file
16
day06/src/com/inmind/constructor03/Demo05.java
Normal file
@@ -0,0 +1,16 @@
|
||||
package com.inmind.constructor03;
|
||||
|
||||
public class Demo05 {
|
||||
public static void main(String[] args) {
|
||||
Student s = new Student();
|
||||
System.out.println(s);
|
||||
System.out.println(s.getAge());
|
||||
System.out.println(s.getName());
|
||||
|
||||
|
||||
Student s1 = new Student("王五", 22);
|
||||
System.out.println(s1.getAge());//22
|
||||
System.out.println(s1.getName());//王五
|
||||
|
||||
}
|
||||
}
|
||||
72
day06/src/com/inmind/constructor03/Student.java
Normal file
72
day06/src/com/inmind/constructor03/Student.java
Normal file
@@ -0,0 +1,72 @@
|
||||
package com.inmind.constructor03;
|
||||
/*
|
||||
Student():就是Student类的"默认"无参构造方法
|
||||
|
||||
普通自定义方法:
|
||||
方法修饰符 返回值类型 方法名(参数列表){
|
||||
return;方法体
|
||||
}
|
||||
|
||||
构造方法:
|
||||
方法修饰符 类名(参数列表){
|
||||
java方法体
|
||||
}
|
||||
|
||||
注意:当源文件(.java文件),进行编译时,编译器扫描整个类的内容,如果没有发现构造方法,那么它会自动帮你添加一个
|
||||
默认无参构造方法,如果你写了构造方法,编译器就不会自动添加默认无参构造方法
|
||||
|
||||
1.构造方法没有返回值类型
|
||||
2.构造方法必须与类名保持一致
|
||||
3.构造方法可以重载
|
||||
|
||||
构造方法的作用:通过new调用构造方法,创建对象,并且对该对象的属性进行赋值
|
||||
*/
|
||||
public class Student {
|
||||
//属性
|
||||
//姓名
|
||||
private String name;
|
||||
//年龄
|
||||
private int age;
|
||||
|
||||
//无参构造方法
|
||||
public Student(){
|
||||
System.out.println("无参构造方法");
|
||||
}
|
||||
//有参构造
|
||||
public Student(String name){
|
||||
System.out.println("有参构造方法");
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//有参构造
|
||||
public Student(int age){
|
||||
System.out.println("有参构造方法");
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
//满参构造方法
|
||||
public Student(String name, int age){
|
||||
System.out.println("满参构造方法");
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
|
||||
//行为
|
||||
//get方法
|
||||
public String getName(){
|
||||
return this.name;
|
||||
}
|
||||
|
||||
|
||||
//get方法
|
||||
public int getAge(){
|
||||
return this.age;
|
||||
}
|
||||
|
||||
|
||||
//学习
|
||||
public void study(String book){
|
||||
System.out.println(this.name+"学生正在学习" + book);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user