为什么不能继承final类,但是可以继承final方法? [英] Why can't a final class be inherited, but a final method can be inherited?

查看:73
本文介绍了为什么不能继承final类,但是可以继承final方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对最终"字词的用法有很大的困惑.类和方法之间的关键字.也就是说,为什么final方法仅支持继承,而不支持final类?

I have a big confusion in the usage of the "final" keyword between classes and methods. I.e., why do final methods only support inheritance, but not final classes?

final class A{
    void print(){System.out.println("Hello, World!");}
}

class Final extends A{
      public static void main(String[] args){
        System.out.println("hello world");
       }
}

错误:

无法从决赛A继承班级总决赛A {最终方法是..

cannot inherit from Final A class Final extennds A{ FINAL METHOD IS..

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

class Honda extends Bike{
    public static void main(String[] args){
        Honda h=new Honda();
        h.run();
    }
}

推荐答案

为什么不能继承final类,但是可以继承final方法?

Why can't a final class be inherited, but a final method can be inherited?

为什么?因为 final 表示类和方法的不同之处.

为什么这意味着不同的事情?因为这是Java语言设计人员选择设计语言的方式!

Why does it mean different things? Because that is how the Java language designers chose to design the language!

Java中的 final 关键字具有三种不同的含义.

There are three distinct meanings for the final keyword in Java.

  • 不能扩展 final 类.

final 方法不能被覆盖.

初始化后,无法将 final 变量分配给该变量.

A final variable cannot be assigned to after it has been initialized.

为什么他们决定使用 final 来表示不同上下文中的不同事物?可能是因为它们不需要保留2或3个不同的关键字.(事后看来,这可能不是最好的决定.但这值得商...……而辩论可能是浪费时间.)

Why did they decide to use final to mean different things in different contexts? Probably so that they didn't need to reserve 2 or 3 distinct keywords. (In hindsight, that might not have been the best decision. However that is debatable ... and debating it is probably a waste of time.)

值得注意的是,其他关键字在Java中具有多种含义.例如, static default (在Java 8中).

It is worth noting that other keywords have multiple meanings in Java; e.g., static and default (in Java 8).

这篇关于为什么不能继承final类,但是可以继承final方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆