代碼
提交代碼
public class ImoocStudent {
// 定義屬性(特征)
String nickname; // 昵稱
String position; // 職位
String city; // 城市
String sex; // 男 | 女
// 無參構造方法
public ImoocStudent() {
// 執行輸出語句
System.out.println("無參構造方法執行了...");
}
// 有參構造方法
public ImoocStudent(String nickname, String position) {
// 將參數變量賦值給實例變量
this.nickname = nickname;
this.position = position;
}
// 有參構造方法
public ImoocStudent(String nickname, String position, String city, String sex) {
this.nickname = nickname;
this.position = position;
this.city = city;
this.sex = sex;
}
// 定義方法(行為)
public void studyCourse() {
System.out.println("學習課程");
}
public void postComment() {
System.out.println("發表評論");
}
public void postArticle() {
System.out.println("發表手記");
}
public static void main(String[] args) {
// 實例化學生對象
ImoocStudent student = new ImoocStudent();
// 給成員屬性賦值
student.nickname = "Colorful";
student.position = "服務端工程師";
student.city = "北京";
student.sex = "男";
// 調用成員屬性
System.out.println("昵稱:" + student.nickname);
System.out.println("職位:" + student.position);
System.out.println("城市:" + student.city);
System.out.println("性別:" + student.sex);
ImoocStudent student1 = new ImoocStudent("慕女神", "UI設計師");
System.out.println("昵稱為:" + student1.nickname);
System.out.println("職位為:" + student1.position);
}
}
運行結果