java子类新增父类没有的方法

错误方法:

public class Main{
   public static void main(String args[]){
      Animal a = new Animal(); // Animal 对象
      Animal b = new Dog(); // Dog 对象
 
      a.move();// 执行 Animal 类的方法
      b.move();//执行 Dog 类的方法
      b.bark();
   }
}

class Animal{
   public void move(){
      System.out.println("动物可以移动");
   }
}
 
class Dog extends Animal{
   public void move(){
      System.out.println("狗可以跑和走");
   }
   public void bark(){
      System.out.println("狗可以吠叫");
   }
}
 

运行结果:
Main.java:9: error: cannot find symbol
b.bark();
^
symbol: method bark()
location: variable b of type Animal
1 error
error: compilation failed

原因:
Animal b = new Dog();这句表现的是JAVA的多态,表示由一个父类的引用指向子类,因为是引用的是动物类型,而动物类没有getC()方法,所以编译器会认为,这个方法是不存在的。
如果要通过编译 必须这样写:Dog b = new Dog();

好比是:我说要一个动物,你给我一只小狗,这是可以的,但是狗会啃骨头,并不等于其他动物都会啃骨头。所以你给我一个动物,然后告诉我它要啃骨头,然而这只动物未必是小狗,所以我告诉你编译错误了

正确方法:

public class Main{
   public static void main(String args[]){
      Animal a = new Animal(); // Animal 对象
      Dog b = new Dog(); // Dog 对象
 
      a.move();// 执行 Animal 类的方法
      b.move();//执行 Dog 类的方法
      b.bark();
   }
}

class Animal{
   public void move(){
      System.out.println("动物可以移动");
   }
}
 
class Dog extends Animal{
   public void move(){
      System.out.println("狗可以跑和走");
   }
   public void bark(){
      System.out.println("狗可以吠叫");
   }
}

运行结果:
动物可以移动
狗可以跑和走
狗可以吠叫

  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值