问下关于对象转型的问题,谢谢

warword0 2008-05-18 02:35:38
class Animal {
public String name;

Animal(String name) {
this.name = name;
}
}

class Dog extends Animal {
public String furcolor;

Dog(String n, String furcolor) {
super(n);
this.furcolor = furcolor;
}
}

class Cat extends Animal {
public String eyescolor;
Cat(String n, String eyescolor) {
super(n);
this.eyescolor = eyescolor;
}
}

public class Test6 {
public static void main(String[] args) {
Test6 t6 = new Test6();
Animal a = new Animal("name1");
Dog d = new Dog("dogname","redfur");
Cat c = new Cat("catname","blueeyes");
t6.t(a); t6.t(d); t6.t(c);

public void t(Animal b) {
System.out.println("name :"+a.name);
if(a instanceof Dog) {
Dog dog = (Dog)a;
System.out.println("furcolor"+dog.furcolor);
}
else if (a instanceof Cat) {
Cat cat = (Cat)a;
System.out.println("eyescolor"+cat.eyescolor);
}
}
}
}

这是练习的小程序,编译的时候告诉我public void t(Animal b)是非法表达式的开始,
Test6.java:34: 非法的表达式开始
public void t(Animal b) {
^
Test6.java:34: 非法的表达式开始
public void t(Animal b) {
^
Test6.java:34: 需要 ';'
public void t(Animal b) {
^
Test6.java:34: 需要 ';'
public void t(Animal b) {
请问哪里错了呢?
...全文
58 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
warword0 2008-05-18
  • 打赏
  • 举报
回复
对,我写错了,写在main里面了,谢谢哦!我是新手,呵呵,很多东西需要总结呢,谢谢大家了,这里真好
Peterry 2008-05-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 pczhouji 的回复:]
你的main函数没有正确结束,少个}
[/Quote]
他好象少到是不少,我数了一下,Test6类那部分,一共是5对,
Peterry 2008-05-18
  • 打赏
  • 举报
回复
要定义在Test6这个类里面才可以
伟大的左前卫 2008-05-18
  • 打赏
  • 举报
回复
你的main函数没有正确结束,少个}
Peterry 2008-05-18
  • 打赏
  • 举报
回复
你把t方法定义在main方法里面了

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧