Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Fragile base class
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Java example== The following trivial example is written in the [[Java programming language]] and shows how a seemingly safe modification of a base class can cause an inheriting subclass to malfunction by entering an [[infinite recursion]] which will result in a [[stack overflow]]. <syntaxhighlight lang="java"> class Super { private int counter = 0; void inc1() { counter++; } void inc2() { counter++; } } class Sub extends Super { @Override void inc2() { inc1(); } } </syntaxhighlight> Calling the dynamically bound method ''inc2()'' on an instance of ''Sub'' will correctly increase the field ''counter'' by one. If however the code of the superclass is changed in the following way: <syntaxhighlight lang="java"> class Super { private int counter = 0; void inc1() { inc2(); } void inc2() { counter++; } } </syntaxhighlight> a call to the dynamically bound method ''inc2()'' on an instance of ''Sub'' will cause an infinite recursion between itself and the method ''inc1()'' of the super-class and eventually cause a stack overflow. This problem could have been avoided, by declaring the methods in the superclass as '''final''', which would make it impossible for a sub-class to override them. However, this is not always desirable or possible. Therefore, it is good practice for super-classes to avoid changing calls to dynamically-bound methods.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)