-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();  
   }  
}  
singhakash
  • 7,891
  • 6
  • 31
  • 65
Jalpesh
  • 63
  • 6

1 Answers1

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();
    }
}
Universal Electricity
  • 775
  • 1
  • 12
  • 26