當前位置:編程學習大全網 - 編程軟體 - 定義壹個動物類,並在類中定義了兩個變量和壹個方法,

定義壹個動物類,並在類中定義了兩個變量和壹個方法,

class Animal {

private String color;

//定義皮毛顏色

private int age;

//定義年齡

Animal () {

color = "White";

age = 1;

}

//Animal默認構造方法

Animal (String c) {

color = c;

age =1;

}

//Animal傳入皮毛顏色時的構造方法

Animal (String c,int a) {

color = c;

age =a;

}

//Animal同時傳入顏色和年齡時的構造方法

void setColor (String color) {

this.color = color;

}

//設置皮毛顏色

void setAge (int age) {

this.age = age;

}

//設置年齡

String getColor () {

return color;

}

//得到皮毛顏色

int getAge() {

return age;

}

//得到年齡

void print() {

System.out.println ("動物皮毛顏色為 " + color + " " + "年齡為 " + age);

}

//打印動物信息

}

public class TestAnimal {

public static void main (String[] args) {

Animal a1 = new Animal ();

Animal a2 = new Animal ("yellow");

Animal a3 = new Animal ("yellow",3);

//對應上面的三個構造方法

a1.print();

a2.print();

a3.print();

//打印a1,a2,a3的信息

a1.setColor ("red");

a1.setAge (3);

//設置a1的皮毛顏色和年齡

a1.print();

//打印驗證

}

}

  • 上一篇:Visual FoxPro的編程和C語言有什麽區別?
  • 下一篇:銑床切削編程
  • copyright 2024編程學習大全網