定義無參構造和有參構造方法
阿新 • • 發佈:2019-01-01
public class h {
String name;
String sex;
int age;
public h(){}; //定義無參構造方法
public h(String n,String s,int a){ //定義有參構造方法,引數為String n、String s、int a.
name=n;
sex=s;
age=a;
}
void getInfo(String n,String s,int a){ //定義方法getInfo(),獲取學生的基本資訊。
name=n;
sex=s;
age=a;
}
void showInfo(){ //定義方法showInfo(),顯示學生資訊。
System.out.println("姓名:"+name);
System.out.println("性別:"+sex);
System.out.println("年齡:"+age);
}
public static void main(String[] args) {
// TODO 自動生成的方法存根
h stu1; //定義屬於類h的物件stu1.
stu1=new h(); //進行例項化物件stu1.
System.out .println("第一個人的資訊");
stu1.getInfo("王五", "男", 19);
stu1.showInfo();
System.out.println("第二個人的資訊");
h stu2=new h("李四","女",20); //定義和例項化物件stu2,並初始化stu2的學生資訊。
stu2.showInfo(); //呼叫方法showInfo()
}
}
“`