how to use final apply to inheritance.
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() // ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
an example of a final class:
Using final to Prevent Overriding
While method overriding is one of Java’s most powerful features.To disallow a method from being overridden,specify final as a modifier at the start of its declaration.
Methods declared as final cannot be overridden.Example1:using final to Prevent Overriding
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() // ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
Here meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time error will result.
Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.
an example of a final class:
final class A
{
// ...
}
// The following class is illegal.
class B extends A // ERROR! Can't subclass A
{
// ...
}
As the comments imply, it is illegal forBto inherit A since A is declared as final.
No comments :
Post a Comment