【问题标题】:What is the difference between override and extend in Java? [duplicate]Java中的覆盖和扩展有什么区别? [复制]
【发布时间】:2015-11-18 04:19:53
【问题描述】:

final关键字可以和method和class一起使用,但是如果和method一起使用那么method不能被覆盖,如果和class一起使用就不能是extend的意思?为此,请让我知道覆盖和扩展之间的主要区别是什么?

例如下面的程序给出编译错误(编译时错误):

Class Bike{  
  final void run(){
    System.out.println("running");
  }  
}  

class Honda extends Bike{  
   void run(){
      System.out.println("running safely with 100kmph");
   }  

   public static void main(String args[]){  
   Honda honda= new Honda();  
   honda.run();  
   }  
}  

【问题讨论】:

  • 冷静,格式化。然后寻求帮助。
  • 您正在寻找文档。
  • @sᴜʀᴇsʜᴀᴛᴛᴀ 讽刺的是你的名字都是大写的 ;)
  • 编译错误是什么?请发布堆栈跟踪。
  • @Samuel 哈哈。没有OP的那么多:P

标签: java


【解决方案1】:
  1. 缩进代码!并修复格式问题!
lass Bike {
    final void run() {
        System.out.println("running");
    }
}

class Honda extends Bike {
    void run() {
        System.out.println("running safely with 100kmph");
    }

    public static void main(String args[]) {
        Honda honda = new Honda();
        honda.run();
    }
}
  1. 修复类声明:
class Bike {
    final void run() {
        System.out.println("running");
    }
}

class Honda extends Bike {
    void run() {
        System.out.println("running safely with 100kmph");
    }

    public static void main(String args[]) {
        Honda honda = new Honda();
        honda.run();
    }
}
  1. 方法上的 final 关键字意味着它不能被覆盖,这意味着:

例如,我有一个班级Dog

public class Dog {
    final void bark() {
        System.out.println("Woof!");
    }
}

我有一只狼:

class Wolf extends Dog {

}

Wolf不能覆盖bark 方法,这意味着无论如何,它都会打印Woof!。但是,这可能是您想要的:

class Bike {
    void run() {
        System.out.println("running");
    }
}

class Honda extends Bike {
    @Override
    void run() {
        System.out.println("running safely with 100kmph");
    }

    public static void main(String args[]) {
        Honda honda = new Honda();
        honda.run();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2012-09-04
    • 2016-06-21
    • 2011-01-12
    • 2010-12-27
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多