instanceof关键字问题

public class InstanceofKeyWordDemo{

public static void main (String[] args){

Person man = new Men();

say(man);

Person women = new Women();

say(women);

}

public static void say(Person p){

p.say();

//判断p对象是否为Women的实例

if (p instanceof Women){

Women women = (Women)p;

women.buy();

}

}

}

abstract class Person{

private String name;

public void setName(String name){

this.name = name;

}

public String getName(){

return name;

}

public abstract void say();//抽象方法

}

class Men extends Person{

public void say(){

System.out.println("我是纯爷们!");

}

}

class Women extends Person{

public void say(){

System.out.println("我是女神经!");

}

//本类扩展方法

public void buy(){

System.out.println("是时候改变一下GDP指数了!");

}

}

运行结果为:

我是纯爷们!

Exception in thread "main" 我是女神经!

java.lang.NoSuchMethodError: Women.buy()V

at InstanceofKeyWordDemo.say(InstanceofKeyWordDemo.java:17)

at InstanceofKeyWordDemo.main(InstanceofKeyWordDemo.java:10)

大神们帮我看看,哪里出错了,谢谢!!!

Oxygen_5
浏览 1481回答 3
3回答

望远

复制运行了下,没问题的,楼主clean一下再运行吧。

Oxygen_5

我的错误是这样的

蜂之谷

貌似没错啊
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java