安全问题,如果一个方法被定义为final,她就不可以被重写,对编译或解释方面也起到象楼主说的效率作用

解决方案 »

  1.   

    final方法本来就被定义为这样的一个作用,楼主为什么还要改变他呢
    难道你对java机制有了新的突破???
    final方法不能被 覆盖 任何一个final方法都是这样
      

  2.   

    如果一个类被声明为final,意味着它不能再派生出新的子类,不能作为父类被继承.
    被声明为final的变量必须在声明时给定初值,而在以后的引用中只能读取,不可修改.
    被声明为final的方法也同样只能使用,不能重载.
      

  3.   

    补充一点:final变量如果是一个引用,那么这个引用就不能指向另外一个对象,但是它所指向的这个对象本事是可以被改变的。
      

  4.   

    final 就是最终的意思,言下之意就是不能被改变了
      

  5.   

    戳穿一个神话:
        form: ibm developerWorks
    Like many myths about Java performance, the erroneous belief that declaring classes or methods as final results in better performance is widely held but rarely examined. The argument goes that declaring a method or class as final means that the compiler can inline method calls more aggressively, because it knows that at run time this is definitely the version of the method that's going to be called. But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant.
      

  6.   

    如果一个类被声明为final,意味着它不能再派生出新的子类,不能作为父类被继承.(同意)被声明为final的方法也同样只能使用,不能重载.(同意)被声明为final的变量必须在声明时给定初值,而在以后的引用中只能读取,不可修改.(不同意)
    final的类变量在声明时可以不设定值,而在构造方法中设定初始值.
      

  7.   

    在子类中如果定义了同名的方法,也就是相当于新建了一个方法,并没有覆盖父类的方法,
    如果父类的方法不声明成final,子类覆盖后不也是调用子类的方法吗?和不声明成final不一样吗?高手指教!
      

  8.   

    提高效率好像是编译器在编译时会选择性地把final变成inline,所以,能不能提高效率是不可控制的。
      

  9.   

    pchobby(你爱我像谁)
    在子类中如果定义了同名的方法,并且参数相同,当然是重载了父类的方法。final的作用是使父类的方法不能被重载,就是说如果你想去重载它就会报编译期错误。
      

  10.   

    使用final 方法的目的有二。第一,为方法上“锁”,禁止派生类进行修改。这是出于设计考虑。当你希望某个方法的功能,能在继承过程中被保留下来,并且不被覆写,就可以使用这个方法。第二个原因就是效率。如果方法是final 的,那么编译器就会把调用转换成“内联的(inline)”。当编译器看到要调用final 方法的时候,它就会(根据判断)舍弃普通的,“插入方法调用代码的”编译机制(将参数压入栈,然后跳去执行要调用的方法的代码,再跳回来清空栈,再处理返回值),相反它会用方法本身的拷贝来代替方法的调用。当然如果方法很大,那么程序就会膨胀得很快,于是内联也不会带来什么性能的改善,因为这种改善相比程序处理所耗用的时间是微不足道的。Java 的设计者们暗示过,Java 的编译器有这个功能,可以智能地判断是不是应该将final 方法做成内联的。不过,最好还是把效率问题留给编译器和JVM去处理,而只把 用于要明确地禁止覆写的场合。
      

  11.   

    to redex(cc): "But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant."----------yes,a class is just a reference,if declared as final it can't be inherited.But inside the class which was composed into another class can we change the value of the fields or the function of the methods?If we can,dose "final" just means that "me can't change,but inside me you can do anything properly"?