定义一个动物类,并在类中定义了两个变量和一个方法,

在主类中创建此动物类的实例对象,调用类中的setColor设置其颜色,方法,设置其年龄,输出该动物类的颜色和年龄。

第1个回答  2011-11-10
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();
//打印验证
}
}
第2个回答  2011-11-10
public class Animal{
private int age;
private String color;

public setColor(String color){
this.color=color;
}
public setAge(int age){
this.age=age;
}
public String toString(){
return age+"\n"+color;
}
}

public static void main(String[],agre){
Animal a = new Animal();
a.setColor("红色");
a.setAge(10);
a.toString();
}
}追问

不对啊!编译的时候有很多问题!

第3个回答  2011-11-10
public class Animal
{
private int age;
private String color;
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age=age;
}
public String getColor()
{
return color;
}
public void setColor(String color)
{
this.color=color;
}
public void inputAndOut(int age,String color)
{
setAge(age);
setColor(color);
System.out.println("年龄:"+this.age+"\n"+"颜色:"+this.color);
}

public static void main(String [] args)
{
Animal animal=new Animal();
animal.inputAndOut(20,"红色");

}
}
第4个回答  2011-11-10
太懒了。这些都在问,上课都在听什么去了追问

汗,太打击人了,就你会嘛.....

追答

这些是基础,要理解,别人可以帮你解决,关键是你自己能不能理解。
public class DoMethod {

public static void main(String[] args) {
System.out.println(new Animal().showAnimal("蓝色", "5"));
}

}
class Animal{
//定义私有参数color
private String color;
//color的get方法
public String getColor() {
return color;
}
//color的set方法
public void setColor(String color) {
this.color = color;
}
//定义私有参数age
private String age;
//age的get方法
public String getAge() {
return age;
}
//age的set方法
public void setAge(String age) {
this.age = age;
}
/**
* 给动物添加color和age的方法,然后输出到Console
* @return 需要打印的字符串
* */
public String showAnimal(String color,String age){
//给动物添加age
this.setAge(age);
//给动物上色
this.setColor(color);
//输出动物的颜色和年龄
return "这是一个" + this.getColor() + "的动物,它已经" + this.getAge() +"岁了。";
}

}

本回答被提问者采纳