-9

final keyword can be used with method and class, but if we used it with method then method can't be override and if we used it with class then it can not be extend means? For that please let me know what is main difference between override and extend?

For example below program give compilation error(Compile time error):

Class Bike{ final void run(){ System.out.println("running"); } } class Honda extends Bike{ void run(){ System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } 
7
  • 2
    Calm down, format. Then ask for help. Commented Aug 24, 2015 at 16:42
  • 2
    You're looking for the documentation. Commented Aug 24, 2015 at 16:44
  • 2
    @sᴜʀᴇsʜᴀᴛᴛᴀ it's ironic that your name is in all caps ;) Commented Aug 24, 2015 at 16:44
  • 2
    What's the compilation error? Post a stack trace please. Commented Aug 24, 2015 at 16:45
  • 2
    @Samuel lol. Not that much as OP's :P Commented Aug 24, 2015 at 16:45

1 Answer 1

0
  1. INDENT THE CODE! AND FIX THE FORMATTING ISSUES!
lass Bike { final void run() { System.out.println("running"); } } class Honda extends Bike { void run() { System.out.println("running safely with 100kmph"); } public static void main(String args[]) { Honda honda = new Honda(); honda.run(); } } 
  1. Fix the class declaration:
class Bike { final void run() { System.out.println("running"); } } class Honda extends Bike { void run() { System.out.println("running safely with 100kmph"); } public static void main(String args[]) { Honda honda = new Honda(); honda.run(); } } 
  1. The final keyword on a method means that it cannot be overridden, meaning this:

For example, I have a class Dog:

public class Dog { final void bark() { System.out.println("Woof!"); } } 

And I have a wolf:

class Wolf extends Dog { } 

The Wolf class cannot override the bark method, meaning that no matter what, it prints Woof!. However, this might be what you want:

class Bike { void run() { System.out.println("running"); } } class Honda extends Bike { @Override void run() { System.out.println("running safely with 100kmph"); } public static void main(String args[]) { Honda honda = new Honda(); honda.run(); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.