Final class – A class
which has final keyword in its definition is called final class and it cannot
be extended. A class should be defined as final if we do not want to override
all methods, our class is in subclass or if we do not want to extend outer
class functionality
Final Method – A method
which has final keyword in its definition is called final method. The rule for
final keyword is it cannot be overridden in subclass, but it is inherited to
subclass, and we can invoke it to execute its logic. If we do not want a subclass
to override super class method and to ensure that all sub classes use the same
super class method logic, then that method should be declared as final method.
Example –
class
Example{
void
m1()
{
System.out.println("in example m1");
}
final void
m2()
{
System.out.println("in example
m2");
}
void
m3()
{
System.out.println("in example m3");
}
}
class
Sample extends Example{
void
m1()
{
System.out.println("in sample m1");
}
/* void m2() //CE{
System.out.println("in
sample m2");
*/
}
class
Tesr1 {
public static void
main(String[] args) {
Sample
s = new
Sample();
s.m1();
s.m2();
s.m3();
}
}
Output –
in sample m1
in example m2
in example m3
No comments:
Post a Comment