Final class A class that cannot be subclassed is called a final class. This is achieved in Java using the keyword final as follows: public final class Aclass { } Any attempt to inherit these classes will cause an error and the compiler will not allow it. Declaring a class final prevents any unwanted extensions to the class. It also allows the compiler to perform some optimizations when a method of a final class is invoked. It also provides some benefit in regard to security and thread safety. final class MySecureClass { A final class is a Java class which cannot be extended. This means that a final class can not become a superclass nor have a subclass. Abstract class public class Vehicle extends Car{ public void getMileage (){ } public static void main(String args []){ Final modifier class CBase { final void methodA() { System.out.println("Final methodA of CBase.") } public void methodB() { System.out.println ("Non-final methodB of CBase.") } } class CDerived extends CBase { void methodA() { System.out.println ("methodA of CDerived.") } void methodB() { System.out.println ("methodB of CDerived.") } public static void main(String args []) { CDerived baseInstance =new CDerived(); baseInstance.methodA(); baseInstance.methodB(); } } The output of this program shows that the final method is not overridden: Final methodA of CBase. methodB of CDerived.
Inner Classes 1. A "regular" inner class is declared inside the curly braces of another class, but outside any method or other code block. 2. An inner class is a full-fledged member of the enclosing (outer) class, so it can be marked with an access modifier as well as the abstract or final modifiers. (Never both abstract and final together— remember that abstract must be subclassed, whereas final cannot be subclassed). 3. An inner class instance shares a special relationship with an instance of the enclosing class. This relationship gives the inner class access to all of the outer class's members, including those marked private. 4. To instantiate an inner class, an instance of the outer class must have a reference. 5. From code within the enclosing class the inner class can be instantiated using only the name of the inner class, as follows: 6. From code outside the enclosing class's instance methods, the inner class can be instantiated only by using both the inner and outer class names and a reference to the outer class as follows: MyOuter mo = new MyOuter (); 7. From code within the inner class, the keyword this holds a reference to the inner class instance. To reference the outer this precede the keyword this with the outer class name as follows: MyOuter.this; class MyOuter { |