Why is Java's "protected" less protected than default? [closed] - java

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.

Related

What is the use of a ForwardingMap in Guava? [closed]

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.

Is this line in the official Java tutorials inaccurate? [closed]

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'm looking here at a summary of "interfaces" in Java: http://docs.oracle.com/javase/tutorial/java/IandI/summary-interface.html
The first line states, "An interface defines a protocol of communication between two objects."
Is that really accurate? From my understanding, an interface is just a contract promising to offer some set of members/methods, which could be used by any arbitrary number of clients (so long as they have proper access per the access modifiers). Am I missing some "other side" of the contract which would make an interface "between two objects"?
EDIT: From the answers/comments (and the votes to close! :-[ ), I think I have it figured out. I think I was just getting hooked on the "between two objects" and assuming it meant "between ONLY two objects", which was apparently a wrong assumption. Thanks!
From my understanding, an interface is just a contract promising to
offer some set of members/methods
That's pretty close to the definition of a protocol.
I wouldn't call it inaccurate. If anything, it's just an oversimplification.
You're right that any number of clients can use the object implementing an interface. And for that matter, you would be right to say that the client doesn't have to be an object (it could be a static method in a class, meaning it's hard to say that the client is an object). But the point about defining a protocol for communication is not wrong, even if requires thinking through a different paradigm.
Whenever you use an object you use it always from another object. You don't call a method from more than an object at the same time.
So if A offers an interface, then B relies on it and C too but A is still offering an interface to B and C separately.
The method signatures defined in the Interface are the enforcement. You have the implementer of the interface on one side, and the client on the other who calls the implementer.

Should I #Deprecate a Superclass Method? [closed]

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.
Let's say I'm extending JFileChooser and making an easy-to-use version, which I'm calling SimpleFileChooser.
It is structured such that it can either be DIALOG_TYPE_OPEN or DIALOG_TYPE_SAVE — hence, JFileChooser's showOpenDialog() and showSaveDialog() methods are superfluous. I replace them with a method called showDialog() which returns a boolean, but this is where I find myself in a dilemma:
Should I override the open/save methods and add #Deprecated tags to
them so that the API user knows they've been superseded? Would that
violate the annotation's original purpose?
Or would a notice in the documentation be enough? If so, where should
this notice be placed: in the class summary or above the overridden
methods? Should I even override the methods in the first place?
Thanks in advance.
I think you are actually building a facade, a simplified version of already existing API. Thus instead of inheritance you should use composition. Hide the original JFileChooser inside your new class and provide simpler API.
As a last resort you can provide public JFileChooser getRaw() method to access wrapped object if some other code needs it.
#Deprecated means you should not use that particular class or method anymore as it will be removed in the future. That annotation is designed for that.
So to answer shortly, if you dont want API users to use the method anymore you should use #Deprecated. Because else you will end up with users that still use methods/classes that you remove in future builds and their projects will be broken when they update.

Circumstances to make a class final? [closed]

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.

Runtime performance of Public vs Private in Java [closed]

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.

Categories

Resources