1 class RedCowForm { 2 static String formName; 3 RedCow cow; //內部類聲明對象 4 RedCowForm() {} //不寫對輸出結果沒有影響 5 RedCowForm(String s) { 6 cow=new RedCow(150,112,5000); 7 formName=s; 8 } 9 public void showCowMess() { 10 cow.speak(); 11 } 12 class RedCow { //內部類的聲明 13 String cowName="紅牛"; 14 int height,weight,price; 15 RedCow(int h,int w,int p) { 16 height=h; 17 weight=w; 18 price=p; 19 } 20 void speak() { 21 System.out.println("偶是"+cowName+",身高:"+height+"cm 體重"+weight+"kg,生活在"+formName); 22 } 23 } //內部類結束 24 } //外部類結束 25 public class Example7_1 { 26 public static void main(String[] args) { 27 RedCowForm form=new RedCowForm("紅牛農場"); 28 form.showCowMess(); 29 form.cow.speak(); 30 } 31 }