Good reasons to prohibit inheritance in Java?

What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?

Asked by: Rafael120 | Posted: 23-01-2022

Answer 1

Your best reference here is Item 19 of Joshua Bloch's excellent book "Effective Java", called "Design and document for inheritance or else prohibit it". (It's item 17 in the second edition and item 15 in the first edition.) You should really read it, but I'll summarize.

The interaction of inherited classes with their parents can be surprising and unpredictable if the ancestor wasn't designed to be inherited from.

Classes should therefore come in two kinds:

  1. Classes designed to be **extended**, and with enough documentation to describe how it should be done

  2. Classes marked **final**

If you are writing purely internal code, this may be a bit of overkill. However, the extra effort involved in adding five characters to a class file is very small. If you are writing only for internal consumption, then a future coder can always remove the 'final' - you can think of it as a warning saying "this class was not designed with inheritance in mind".

Answered by: Adrian912 | Posted: 24-02-2022

Answer 2

You might want to make a method final so that overriding classes can't change behavior that is counted on in other methods. Methods called in constructors are often declared final so you don't get any unpleasant surprises when creating objects.

Answered by: Emily277 | Posted: 24-02-2022

Answer 3

One reason to make a class final would be if you wanted to force composition over inheritance. This is generally desirable in avoiding tight coupling between classes.

Answered by: Melanie491 | Posted: 24-02-2022

Answer 4

There are 3 use cases where you can go for final methods.

  1. To avoid derived class from overriding a particular base class functionality.
  2. This is for security purpose, where base class is giving some important core functionality of the framework where derived class is not supposed to change it.
  3. Final methods are faster than instance methods, as there is no use of virtual table concept for final and private methods. So where ever there is a possibility, try to use final methods.

Purpose for making a class final:

So that no body can extend those classes and change their behavior.

Eg: Wrapper class Integer is a final class. If that class is not final, then any one can extend Integer into his own class and change the basic behavior of integer class. To avoid this, java made all wrapper classes as final classes.

Answered by: Kimberly138 | Posted: 24-02-2022

Answer 5

you might want to make immutable objects (, you might want to create a singleton (, or you might want to prevent someone from overriding the method for reasons of efficiency, safety, or security.

Answered by: Dexter581 | Posted: 24-02-2022

Answer 6

Inheritance is like a chainsaw - very powerful, but awful in the wrong hands. Either you design a class to be inherited from (which can limit flexibility and take a lot longer) or you should prohibit it.

See Effective Java 2nd edition items 16 and 17, or my blog post "Inheritance Tax".

Answered by: Lenny391 | Posted: 24-02-2022

Answer 7

Hmmm... I can think of two things:

You might have a class that deals with certain security issues. By subclassing it and feeding your system the subclassed version of it, an attacker can circumvent security restrictions. E.g. your application might support plugins and if a plugin can just subclass your security relevant classes, it can use this trick to somehow smuggle a subclassed version of it into place. However, this is rather something Sun has to deal with regarding applets and the like, maybe not such a realistic case.

A much more realistic one is to avoid an object becomes mutable. E.g. since Strings are immutable, your code can safely keep references to it

 String blah = someOtherString;

instead of copying the string first. However, if you can subclass String, you can add methods to it that allow the string value to be modified, now no code can rely anymore that the string will stay the same if it just copies the string as above, instead it must duplicate the string.

Answered by: Sienna952 | Posted: 24-02-2022

Answer 8

To stop people from doing things that could confuse themselves and others. Imagine a physics library where you have some defined constants or calculations. Without using the final keyword, someone could come along and redefine basic calculations or constants that should NEVER change.

Answered by: Paul336 | Posted: 24-02-2022

Answer 9

Also, if you are writing a commercial closed source class, you might not want people to be able to change the functionality down the line, especially if u need to give support for it and people have overridden your method and are complaining that calling it gives unexpected results.

Answered by: Robert724 | Posted: 24-02-2022

Answer 10

If you mark classes and methods as final, you may notice a small performance gain, since the runtime doesn't have to look up the right class method to invoke for a given object. Non-final methods are marked as virtual so that they can be properly extended if needed, final methods can be directly linked or compiled inline in the class.

Answered by: Carina721 | Posted: 24-02-2022

Answer 11

You want to make a method final so that overriding classes does not change its behavior. When you want to be able to change the behavior make the method public. When you override a public method it can be changed.

Answered by: Patrick443 | Posted: 24-02-2022

Similar questions

inheritance - Would syntax for composition be a useful addition to Java?

Closed. This question is opinion-based. It is not c...

inheritance - Java dynamic binding and method overriding

Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java. And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing... Here's the problem I was given: /* What is the ou...

Java Listener inheritance

I have a java class which fires custom java events. The structure of the code is the following: public class AEvent extends EventObject { ... } public interface AListener extends EventListener { public void event1(AEvent event); } public class A { public synchronized void addAListener(AListener l) { .. } public synchronized void removeAListener(AListener l) { .. } protected void fireA...

inheritance - Extending enum in Java

public enum myEnum { VAL1(10), VAL2(20), VAL3("hai") { public Object getValue() { return this.strVal; } public String showMsg() { return "This is your msg!"; } }; String strVal; Integer intVal; public Object getValue() { return this.intVal; } private myEnum(int i) { this.intVal = new Integer(i); } private myE...

inheritance - Java Protected Access Not Working

In java, there's three levels of access: Public - Open to the world Private - Open only to the class Protected - Open only to the class and its subclasses (inheritance). So why does the java compiler allow this to happen? public class TestBlah { public static void main(String[] args) { Blah a = new Blah("Blah"); Bloo...

inheritance - "Dynamic" Casting in Java

Hullo all, Wondering if there are any Java hackers who can clue me in at to why the following doesn't work: public class Parent { public Parent copy() { Parent aCopy = new Parent(); ... return aCopy; } } public class ChildN extends Parent { ... } public class Driver { public static void main(String[] args) { ChildN orig = new ChildN(); ... ...

java - Class inheritance with Hibernate and hbm2java

I am generating my domain objects from my hbm files with hbm2java and now I want them to all inherit a base class. This class will have some utility methods for dealing with listeners. It does not really need to be persisted and I am hoping that I would not have to do a hbm file for it since it will be abstract and only have methods. Is there a meta tag or something to have all generated class extend another class?

Abstract classes and methods in Java, Inheritance

I have class B, which inherits from class A. The superclass A is abstract, containing one abstract method. I don't want to implement the abstract method in class B, therefore I need to declare class B as abstract as well. Declaring class B abstract, two things are working for me (the programs compile and run correctly): 1.) I don't declare any abstract methods in class B, even thought the class is abstract. This wo...

inheritance - Java not inheriting accessor methods?

Given a class "Bar" that extends class "Foo" which implements interface "DeeDum" public interface DeeDum { public String getDee(); public String getDum(); } public class Foo implements DeeDum { public String dee = "D"; public String dum; public String getDee() { return dee; } public String getDum() { return dum; } } public class Bar extends Foo { public String dee = "DEE"; ...

How to by-pass inheritance in java when invoking a method

class Super { public void anotherMethod(String s) { retValue(s) } public String retValue(String s) { return "Super " + s; } } class Sub extends Super { public void anotherMethod(String s) { retValue(s) } public String retValue(String s) { return "Sub " + s; } }

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)