黑马程序员技术交流社区
标题:
请查看代码,当父类引用对象,引用jump方法就会出现错误
[打印本页]
作者:
251855915
时间:
2016-4-10 22:42
标题:
请查看代码,当父类引用对象,引用jump方法就会出现错误
class Test1_Animal1 {
public static void main(String[] args) {
Animal1 a = new Cat("汤姆",3);
a.sleep();
a.eat();
//a.jump(); //不可以调用jump方法,因为父类Animal中没有jump方法,编译不能通过
System.out.println("--------------------------------");
Cat c = new Cat("加菲",3);
c.sleep();
c.eat();
c.jump();
System.out.println("--------------------------------");
Dog d = new Dog("八公",9);
d.sleep();
d.eat();
d.jump();
}
}
//创建父类animal,成员变量姓名,年龄,成员方法睡觉,抽象方法吃饭
abstract class Animal1 {
private String name;
private int age;
public Animal1(){}
public Animal1(String name,int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public void sleep(){
System.out.println(name+"睡觉");
}
public abstract void eat();
}
//接口,jump
interface Jump {
public void jump();
}
//创建类cat,父类为Animal,接口有jump,重写父类抽象方法eat,重写接口方法jump
class Cat extends Animal1 implements Jump {
public Cat(){}
public Cat(String name,int age){
super(name,age);
}
public void eat(){
System.out.println(this.name+"吃鱼");
}
public void jump(){
System.out.println(this.name+"跳高");
}
}
//创建类dog,父类为Animal,接口有jump
class Dog extends Animal1 implements Jump {
public Dog(){}
public Dog(String name,int age){
super(name,age);
}
public void eat(){
System.out.println(this.name+"吃肉");
}
public void jump(){
System.out.println(this.name+"跳高");
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2