Before understanding about final method you need to know about over riding because any method in java is having some concern with over riding . So to know more about over riding just Click here. As we know that we can easily over ride non-final method but once method is declared as final it cannot be over ride.And we are over riding any method of super-class in the sub-class only. For ex-

Syntax of Final method :
< final >  < return_type > method_ name ( ) { 


class A{

void display(){            // Non-Final method of super-class
System.out.println("superclass method");

    }
}

public class prog7 extends A{

void display(){          // Non-Final method of super-class

System.out.println("sub-class method");

}

public static void main(String sush[]) {

prog7 p = new prog7();

p.display();

   }

}

In the above class A is a super class and Class prog7 is a sub-class extending A . Here we had defined display() with same return type and no argument , the only change is the implementation. So for over riding we need to care about all these things i.e every thing related to method should be same but with different implementation.

Here we are over riding super-class method i.e display() , and if we try to execute the above code it will execute the statements of sub-class display method and print "sub-class method" .

What if we make the display() as final ? will it be over ride or not ?
No it will not override because once it declared as final it cannot be modified further in the sub-class with different implementation. For ex-

class A{

final void display(){        // Final method of super-class

System.out.println("superclass method");

    }

}

public class prog7 extends A{

void display(){           // Cannot be over ride in sub-class

System.out.println("sub-class method");

}

public static void main(String sush[]) {

prog7 p = new prog7();

p.display();

   }

}

While compiling the above code compiler give the complication error saying "display() in prog7 cannot override display() in A; overridden method is final " .

1 comment:

Blog Archive

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic