As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Are there any general guidelines as to when to make a class final?
I thought it was if you did not want people extending your class, but that seems slightly.... naive??
Making a class final only prevents it from being extended as you note. Why would you want to do that?
One typical use case is to guarantee immutability. If you design an immutable class but don't make it final, it can be extended in a mutable way. This can in turn lead to a subclass corrupting a class invariant or creating concurrency issues.
You could also simply mark a class as final to document the fact that it is not designed to be extended. See for example Effective Java #17: "Design and document for inheritance or else prohibit it".
Ideally, you have read Josh Bloch and designed your class for perfectly working inheritance. But, in practice, my (IMHO) answer to making a class final is
Do you trust (or want) others to extend it?
If it is a super-critical class like String or some security related class, yes, definitely make it final.
If you are doing real fancy stuff and the class would be difficult to extend properly, consider making it final, depending on the skills you expect those using the class to have. Also depends on whether this is a general purpose library or some company/project specific code, and whether is it for a website with Squirrel videos or a heart pacemaker - i.e., how badly will a poor subclass break things???
If you aren't doing anything all that fancy, don't annoy users by making it final. I have often cursed Java for making classes like Double final.
It is well established that inheritance breaks encapsulation. Allan Snyder in his paper Encapsulation and inheritance in object-oriented programming languages demonstrates the care you must exercise with inheritance.
Josua Bloch in his book Effective Java recommends that you design and document your classes to be inherited or else you prohibit it, precisely referring to the problems already known to Snyder.
If at some point you are not sure how your classes can be extended in the future or if you have no intention whatsoever that they actually be extended, then you are probably better off making them final. You can always open them for extension later, but the contrary (above all if you are building an open system) can be a real cause of pain, if not impossible depending of the circumstances.
The researches Mikhajlov and Sekerinski in their paper A Study of the Fragile Base Class demonstrate the array of problems you may have when improperly using inheritance which may give you a broader idea of why this could be important.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
In Java, we have four access specifiers: public, protected, package-private (default), and private. This is well known and not an issue for me.
My question is with regard to the naming of protected. As shown in the table here, giving a field the default access specifier of package-private prevents subclasses outside of the package from using it, but applying the keyword protected doesn't actually protect it – on the contrary, it opens it up to subclasses of any package.
So, why doesn't protected protect things; why is it less restrictive than no modifier at all?
If we accept that those are the four access levels that should exist (private, package-private, package-private-plus-subclasses, and public), and we accept that package-private should be the default access level when you don't specify something else, then this question becomes: "why is package-private-plus-subclasses called protected?" And the answer to that is that it borrowed/inherited the term from C++ (which doesn't have a concept of "packages", but uses protected to mean "private-plus-subclasses").
(I'm posting this answer as community wiki to encourage others to add to it, since I'm guessing that there's more to the story than just this. Also, because someone may want to add some justification of why these are the four access levels that should exist — e.g., why we have package-private-plus-subclasses but no private-plus-subclasses — and of why package-private should be the default.)
Since this is a rather open-ended question I'll offer some semi-relevant historical context. In Java 1.0 there was an additional access modifier, private protected. This was protected minus package access. This modifier was confusing, poorly implemented and removed by 1.1. This helps paint the picture that the package is the logical modular unit which is therefore the default level of access.
At the end of the day it comes down to a personal choice of what made sense to the developers. Everyone thinks differently so a naming convention that makes perfect sense to me may be deeply confusing for you (and vice versa).
Protected is more restrictive than public. That is why it is called what it is.
I wish the language designers would have named the default access specifier as "package-protected', because the default is very confusing to a lot of programmers. I would more be in favor for protected being the default, or there being no default at all.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am scratching my head over understanding the use of a ForwardingMap?
What are the cases that one might use it?
ForwardingXxx classes provide decorator pattern implementations for all JDK and Guava collections, including Map.
Read more on Guava's wiki and in Effective Java 2nd Edition, Item 16: Favor composition over inheritance:
To summarize, inheritance is powerful, but it is problematic because
it violates encapsulation. It is appropriate only when a genuine
subtype relationship exists between the subclass and the superclass.
Even then, inheritance may lead to fragility if the subclass is in a
different package from the superclass and the superclass is not
designed for inheritance. To avoid this fragility, use composition and
forwarding instead of inheritance, especially if an appropriate
interface to implement a wrapper class exists. Not only are wrapper
classes more robust than subclasses, they are also more powerful.
Basically it lets you customize possibly non-extendable Maps without adding dependencies on actual Map implementation.
The default Map classes are all final. That means you can't extend them. When you want to create a map with some special behavior, you need to write your own class which implements the whole Map interface and forwards all methods to an internal Map.
The ForwardingMap makes this simpler for you by already being an extendable class which implements Map and forwards everything to an internal map. That means you can create your own Map implementation by extending it. When you do that, you only need to implement selected methods and not all of them.
One use-case might be a map which automatically validates all entries you put into it or one which automatically updates a database when it's changed.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In class the prof said one reason he likes C better than Java is that C has a preprocesor, and in particular macros. Is there any benefit to macros over declaring afinal/const variable with the desired value? I know Java doesn't have global variables so would there ever be a situation where using a variable in substitution for macros would not work?
Using a macro system in C has been a long standing tradition that often leads to incomprehensible build chains, and very project specific build configurations. I would argue that the reason that macros exist in C is to overcome the shortcomings it has as a language for when you need things that macros provide (for example, you can use interfaces in Java, which solve the problem of needing to make a "generic" instance of something).
Still, there are times when having a macro system just seems to fit a problem easier. I do know of some shops that do this -- for example -- when they need to support multiple different versions of an API. Generally you can overcome this problem in Java by proper use of interfaces and a good abstraction layer in your design. However, there are macro systems for Java out there! You can use them, if you please. You might also note that, as far as macros go, C macros aren't really anything very special.
(In my opinion your teacher was somewhat off base...)
There's no reason you can't run your Java code through a macro preprocessor; it's just not done as part of the language.
With that said, most of the reasons macros are valuable in C are matters of the C language, and most people's use of them is extremely ugly and counterproductive, though they do have many good uses too.
Anyway, I would really question the expertise of someone who compares C and Java on the basis that one has macros and the other doesn't. In the big scheme of things, that seems to be one of the most trivial differences between the languages. Highlighting it suggests to me that the person does not understand the real differences between the languages; perhaps he likes C but doesn't know how to name any of the actual features C has over Java - things like storage duration and representation of types.
Macros in C are not just global constants. They can also define functions, like
#define SHOW_DEFINE(x) printf("%s=%s\n", #x, STR(x))
This can be quite helpful during debugging. It is unfortunatly also easy to hurt yourself quite badly with Macros.
#define MULTIPLY(X,Y) X*Y
works fine for, lets say MULTIPLY(1,2) but leads to problems if one uses MULTIPLY(1-1,2-2) = 1-2*2-2 = 1-4-2 instead of the expected 0*0.
Usually, with modern tools such functions are not longer necessary and with a good design and some abstraction and the interfaces that Java provides it is in general not necessary to have macros in Java. Java is designed, afaik, to make it as hard as possible to shoot yourself.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Is there a runtime performance differance between public and private variables/methods?
I know that it is considered good practice to keep things private if possible, but is there any optimisation related reason.
Like most of these questions I would say; write clear, simple code and it will perform well also.
If some one tells you something is a good idea for performance reasons, make sure this is backed up with real numbers, is still the case for the version of Java you are using (much of this advise is out of date), and it is appropriate for your application.
Often "performance reasons", is an excuse to write obscure code, when actually it may be no faster or can even be much slower (as it confuses the JVM optimiser, just as it will confuse you)
Some people are so sceptical of performance optimisation that you have the quote "premature optimisation is the root of all evil" This is an exaggeration, but it is a good warning, not to worry about performance concerns unless you really know you need to improve performance, and your changes really make a difference.
To this specific question, you can't call a private method from another class. So basically, you can't from another outer class, and from another class in the same outer class, and accessor is created which would normally be inlined if called enough.
I don't think there is directly. Access modifiers are more of a compile-time thing in my view anyway.
Even if there was, don't go that way, there is a very good reason (several of them probably) that you shouldn't make class fields public.
There is an incredibly small performance impact because you have to call the getter and setter methods for a field, but unless you do complex operations there, it definitely won't be noticable. It's a matter of miliseconds at most.
There is no difference runtime performance between private and public variables/methods.It only depend on your program requirements. for example, you have a method that is required for the entire program then you should use public method.Its reduce code duplication. But you have a method that is required only one class then you should use private method.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
When i came across the reason why Multiple Inheritance was not included in Java, the reasons given were to keep 'simplicity' and 'reduce complication'.
However working with Java environment coming from a C++ background, don't you think that Interface concept to support multi inheritance has complicated the matter rather than solving it? Does it lead to the inference that:
We must NOT use multiple inheritance in Java, and our code architecture should be designed accordingly?
Use concept of Interface for multiple inheritance, which i think is less favorable (atleast for me) compared to the st
You should read Bjarne Stroustrup's point of view about multiple inheritance:
Do we really need multiple inheritance?
Not really. We can do without
multiple inheritance by using workarounds, exactly as we can do
without single inheritance by using workarounds. We can even do
without classes by using workarounds. C is a proof of that contention.
However, every modern language with static type checking and
inheritance provides some form of multiple inheritance. In C++,
abstract classes often serve as interfaces and a class can have many
interfaces. Other languages - often deemed "not MI" - simply has a
separate name for their equivalent to a pure abstract class: an
interface. The reason languages provide inheritance (both single and
multiple) is that language-supported inheritance is typically superior
to workarounds (e.g. use of forwarding functions to sub-objects or
separately allocated objects) for ease of programming, for detecting
logical problems, for maintainability, and often for performance.
quoted from http://www2.research.att.com/~bs/bs_faq2.html#multiple
Multiple implementation inheritance and multiple interface inheritance are not the same beasts.
However, it would significantly complicate the GC and other language implementation if they were to add multiple implementation inheritance.
I think the choice of Java (and many other OO languages) designers was mainly motivated by the fragile base problem. It's true we don't need multiple inheritance, but for that's worth to note we don't need single either. Object Oriented programming it's about identities of entities. Inheritance can be seen as syntax sugar in this regard.
The interface concept in java is NOT meant for providing multiple inheritance feature.