{
private String msg="";
public void setMsg(String msg){ thismsg=msg; }
void fly()
{
Systemoutprintln(thismsg);
}
}
//test class
public void main(String[] args)
{
animal a=new animal();
aname = "哈哈";
aage = 12;
acolor = "red";
Systemoutprintln(a);
//++++++
bird daYan = new bird();
daYanname = "大雁"
daYansetMsg(“一会排成个一字,一会排成个人字”);
daYanfly();
bird ji = new bird();
jiname = "鸡";
jisetMsg(“md老子不会飞”);
jifly();
//++++++++
}
class 动物
class 孔雀 extends 动物 (重写动物的方法)
class 河马 extends 动物 (重写动物的方法)
test:里面 用动物 创建 孔雀 和 河马 然后调用其方法。
public class Animal{
private String eyes;
public String getEyes(){
rentrun thiseyes;
}
public void setEyes(String eyes){
thiseyes = eyes;
}
public void run(){
Systemoutprintln("I can run!~");
}
public static void main(String[] args) {
Animal animal = new Animal();
animalrun();
}
}
public class Animal
{
public String name;
public int legs;
public String sound;
public Animal(String name, int legs, String sound){
thisname = name;
thislegs = legs;
thissound = sound;
}
public String toString(){
return name + "\t" + legs + "\t" + sound;
}
public static void main(String[]args)
{
//init
Animal[] animals = new Animal[3];
animals[0] = new Animal("加菲猫",4, "喵喵喵");
animals[1] = new Animal("唐小鸭",2, "嘎嘎嘎");
animals[2] = new Animal("海豚奇奇",0, "海豚音");
byte[] b = new byte[1024];
String[] names = {"猫", "鸭子", "海豚"};
int[] legs = {4,2,0};
String name;
int leg;
String sound;
while(true){
try{
Systemoutprintln("动物名称\t腿的条数\t动物叫");
for (int i = 0; i < animalslength; i++) {
Systemoutprintln(animals[i]toString());
}
Systemoutprintln("0-修改,其他数字-退出");
int n = Systeminread(b);
String s = new String(b,0,n);
int oper = IntegerparseInt(strim());
if (oper != 0) {
Systemoutprintln("退出!");
return;
}
for (int i = 0; i < animalslength; i++) {
Systemoutprintln("请输入"+names[i]+"的名字");
n = Systeminread(b);
s = new String(b,0,n);
name = strim();
if (namelength() == 0) {
throw new Exception(names[i]+"必须有名字");
}
Systemoutprintln("请输入"+names[i]+"的腿数");
n = Systeminread(b);
s = new String(b,0,n);
leg = IntegerparseInt(strim());
if (leg != legs[i]) {
throw new Exception(names[i]+"必须有"+legs[i]+"条腿");
}
Systemoutprintln("请输入"+names[i]+"的叫声");
n = Systeminread(b);
s = new String(b,0,n);
sound = strim();
if (soundlength() == 0) {
throw new Exception(names[i]+"必须有声音");
}
animals[i]name = name;
animals[i]legs = leg;
animals[i]sound = sound;
}
}
catch(Exception e){
eprintStackTrace();
}
}
}
}
凑合写的
instanceof 不难吧就是验证类是否为类或者父类的实例
我看你ppt要求的是自定义异常抛出,接口继承应该很简单,抛出异常参考我的代码即可
以上就是关于如何用java写一个动物的抽象类,包含重量,年龄等属性,以及移动,捕食方法。全部的内容,包括:如何用java写一个动物的抽象类,包含重量,年龄等属性,以及移动,捕食方法。、用JAVA语言设计三个类,分别表示动物、孔雀、河马,加入合理的属性和方法,用继承关系,用这三个类说明运、用java创建一个动物类animal,它具有眼睛eyes属性(string类型,描述眼睛是大或小),还具有跑run的方法...等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)