PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] Why can't a final class be inherited, but a final method can be inherited?

 July 08, 2022     class, final, inheritance, java     No comments   

Issue

I have a big confusion in the usage of the "final" keyword between classes and methods. I.e., why do final methods only support inheritance, but not final classes?

final class A{
    void print(){System.out.println("Hello, World!");}
}

class Final extends A{
      public static void main(String[] args){
        System.out.println("hello world");
       }
}

ERROR:

cannot inherit from Final A class Final extennds A{ FINAL METHOD IS..

class Bike{
    final void run(){System.out.println("run");}
}

class Honda extends Bike{
    public static void main(String[] args){
        Honda h=new Honda();
        h.run();
    }
}

Solution

Why can't a final class be inherited, but a final method can be inherited?

Why? Because final means different things for classes and methods.

Why does it mean different things? Because that is how the Java language designers chose to design the language!

There are three distinct meanings for the final keyword in Java.

  • A final class cannot be extended.

  • A final method cannot be overridden.

  • A final variable cannot be assigned to after it has been initialized.

Why did they decide to use final to mean different things in different contexts? Probably so that they didn't need to reserve 2 or 3 distinct keywords. (In hindsight, that might not have been the best decision. However that is debatable ... and debating it is IMO a waste of time.)

It is worth noting that other keywords have multiple meanings in Java; e.g., static and default (in Java 8).



Answered By - Stephen C
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing