Java 類和對象3,java對象3
編寫Java應用程式。首先,定義描述學生的類——Student,包括學號(int)、姓名(String)、年齡(int)等屬性;二個方法:Student(int stuNo,String name,int age)
用於對對象的初始化,outPut()用於輸出學生資訊。其次,再定義一個主類—TestClass,在主類的main方法中建立多個Student類的對象,使用這些對象來測試Student類的功能。
1 //建立類 2 int stuNo; 3 String stuName; 4 int stuAge; 5 //構造方法 6 student(int stuNo,String name,int age) 7 { 8 this.stuNo=stuNo; 9 stuName=name;10 stuAge=age;11 }12 void outPut()13 {14 System.out.println(stuName+"\t"+stuNo+"\t"+stuAge);15 }16 17 public static void main(String[] args) {18 student xs1=new student(10001,"張三",25);19 student xs2=new student(10002,"李四",27);20 student xs3=new student(10003,"王五",22);21 student xs4=new student(10004,"馬六",19);22 student xs5=new student(10005,"馮七",22);23 student xs6=new student(10006,"秦八",26);24 25 System.out.println("姓名:\t學號:\t年齡:");26 xs1.outPut();27 xs2.outPut();28 xs3.outPut();29 xs4.outPut();30 xs5.outPut();31 xs6.outPut();32 }
運行結果: