This question already has answers here:
Is there a way to simulate the C++ 'friend' concept in Java?
(18 answers)
Closed 9 years ago.
Ok, let's leave the debate of whether friendship breaks encapsulation, and actually try elegantly come up with a coherent design. It is a two fold function:
1) General question on how to implement:
public class A
{
friend class B;
}
2) Why do I need this functionality? Some of my classes implement Serializable interface. However, I want to make Serializable methods protected in the Derived class so that I don't expose them to a client (as well as in the documentation -- javadoc). However, internal classes should be able to access them. What is the General way to solve this problem in java?
Note: I am using friendship as defined in the current C++ standard.
Thanks
The general solution is to make the methods package-private (which is the default protection level in Java). That way any code in the same package can access them, but not external code.
Java does not allow arbitrary sharing of methods with specific external classes.
EDIT: Protected members are actually less private than package-private. If you have protected members, you can access them from derived classes outside your package, and from any class inside the package. So that may be a solution to your problem - derive the class in another class in the package you want to export to.
Generally, Java considers the package as the main module of encapsulation. The public/protected interface is for classes outside the package, and the default protection level allows access within the package.
It seems as if you want a façade.
You appear to have a class that needs to give public access to various other classes (even in different packages) involved in the implementation. But you don't want clients having access.
Therefore, make the implementation as complicated as you like. Have a façade class, with just the interface you want, delegate to the implementation.
This link gives a way to emulate friend access in Java: http://macchiato.com/columns/Durable7.html
The code copied from the link (in case the site is not accessible):
public class A {
private int privateInt = 31415;
public class SomePrivateMethods {
public int getSomethingPrivate() { return privateInt; }
private SomePrivateMethods() {} // no public constructor
}
public void giveKeyTo(B other) {
other.receiveKey(new SomePrivateMethods());
}
}
public class B {
private A.SomePrivateMethods key;
public void receiveKey(A.SomePrivateMethods key) {
this.key = key;
}
public void usageExample() {
A anA = new A();
//int foo = anA.privateInt; // doesn't work, not accessible
anA.giveKeyTo(this);
int fii = key.getSomethingPrivate();
System.out.println(fii);
}
}
One thing I noticed... it sounds like you do not want the methods that you have to override because you are implementing Serializable to be made public. One thing though, Serializable is a marker interface (it provides no methods to be overridden) and the readObject and writeObject methods are supposed to be private.
Am I missing something?
There are two solutions to your question that don't involve keeping all classes in the same package.
The first is to use the Friend Accessor/Friend Package pattern described in (Practical API Design, Tulach 2008).
The second is to use OSGi. There is an article here explaining how OSGi accomplishes this.
Related Questions: 1, 2, 3, and 4.
Related
Let's take an example:
public interface Testerface {
default public String example() {
return "Hello";
}
}
public class Tester implements Testerface {
#Override
public String example() {
return Testerface.super.example() + " world!";
}
}
public class Internet {
public static void main(String[] args) {
System.out.println(new Tester().example());
}
}
Simply enough, this would print Hello world!. But say I was doing something else with the return value of Testerface#example, for instance initializing a data file and returning a sensitive internal value that shouldn't leave the implementing class. Why does Java not allow access modifiers on default interface methods? Why can't they be protected/private and potentially elevated by a subclass (similar in how a class that extends a parent class can use a more visible modifier for an overridden method)?
A common solution is moving to an abstract class however in my specific case, I have an interface for enums, so that does not apply here. I imagine it was either overlooked or because the original idea behind interfaces that they are a "contract" of available methods, but I suppose I want input as to what's going on with this.
I've read "Why is “final” not allowed in Java 8 interface methods?", which states:
The basic idea of a default method is: it is an interface method with a default implementation, and a derived class can provide a more specific implementation
And it sounds to me like visibility wouldn't break that aspect at all.
As with the linked question since it looks like it had trouble being closed, an authoritative answer would be appreciated in this matter, rather than opinion-based ones.
As we saw in What is the reason why “synchronized” is not allowed in Java 8 interface methods? and Why is "final" not allowed in Java 8 interface methods?, extending interfaces to define behavior is more subtle than it might first appear. It turns out that each of the possible modifiers has their own story; its not simply a matter of blindly copying from how classes work. (This is at least obvious in hindsight, as tools for OO modeling that work for single inheritance do not automatically work for multiple inheritance.)
Let's start with the obvious answer: interfaces have always been restricted to only having public members, and while we added default methods and static methods to interfaces in Java 8, that doesn't mean we have to change everything just to be "more like" classes.
Unlike with synchronized and final, which would have been serious mistakes to support for default methods, weaker accessibilities, especially private, are reasonable features to consider. Private interface methods, whether static or instance (note that these would not be defaults, since they do not participate in inheritance) are a perfectly sensible tool (though they can be easily simulated by nonpublic helper classes.)
We actually did consider doing private interface methods in Java 8; this was mostly something that just fell off the bottom of the list due to resource and time constraints. It is quite possible this feature might reappear on the to-do list some day. (UPDATE: private methods in interfaces were added in Java 9.)
Package and protected methods, however, are more complicated than they look; the complexity of multiple inheritance and the complexity of the true meaning of protected would interact in all sorts of no-so-fun ways. So I wouldn't hold your breath for that.
So, the short answer is, private interface methods is something we could have done in 8, but we couldn't do everything that could have been done and still ship, so it was cut, but could come back.
I was assigned to a project, and it is my job to implement a feature to the already existing system. This functionality needs to be added to two seperate classes. Both of these classes extend the same super class, but it does not make sense to add the feature to this superclass. What is the best way I can implement the same functionality into these two seperate classes without too much code duplication. The simple way would be implementing this functionality into a static class and then using the static methods in the two classes that need this extra functionality, but that sort of seems like bad design.
Is there any sort of design I can use to implement something like this, or is me running into this problem just showing a larger issue in the hierarchy that should be fixed rather than try to work on top of it?
Java does not have stand-alone "static" classes, so that's a non-starter since it's not even possible. As for use of static methods, that's fine if you're talking about stateless utility methods.
Myself, I guess I'd solve this with composition and interfaces:
Create an interface for the functionality that I desire
Create concrete instance(s) of this interface
Give the two classes fields of the interface
Plus getter and setter methods for the interface.
If the classes had to have the new behaviors themselves, then have them implement the interface, and then have these classes obtain the behaviors by "indirection" by calling the methods of the contained object in the interface methods.
I'm sorry that this answer is somewhat vague and overly general. If you need more specific advice from me or from anyone else here, then consider telling us more of the specifics of your problem.
Determine what common features of these two classes the new functionality relies on. Then, extract those features to an interface, modify the two classes to implement that interface, and put the new functionality code in its own class (or possibly a static method somewhere, e.g. NewFeature.doTheThing(NewFeaturable toWhat)) and make it operate on those interfaces.
If the existing classes have to obtain information from / call methods related to the "new feature", then give them a NewFeature field that is an instance of the new feature class and have them interact with that object. Pseudo-ish code:
interface NewFeaturable {
int getRelevantInfo ();
}
class NewFeature {
final NewFeaturable object;
NewFeature (NewFeaturable object) { this.object = object; }
void doSomething () { int x = object.getRelevantInfo(); ... }
}
class ExistingClass extends Base implements NewFeaturable {
final NewFeature feature;
ExistingClass () { ...; feature = new NewFeature(this); }
#Override int getRelevantInfo () { ... }
void doSomethingNew () { feature.doSomething(); }
}
Be wary of new NewFeature(this) there, as subclasses of ExistingClass will not be fully constructed when it is called. If it's an issue, consider deferring initialization of feature until it is needed.
A lot of the specifics depend on your exact situation, but hopefully you get the general idea.
I am going through head into java and came across this example
interface Nose{
public int iMethod();
}
abstract class Picasso implements Nose{
public int iMethod(){
return 7;
}
}
class Clowns extends Picasso{}
class Acts extends Picasso{
public int iMethod(){
return 5;
}
}
Because nothing is declared public, doesn't that mean that none of these classes can be called from another file? I have another file
public class Of76 extends Clowns{
public static void main(String[] args) {
Nose [] i = new Nose[3];
i[0] = new Acts();
i[1] = new Clowns();
i[2] = new Of76();
for(int x = 0; x < 3; x++) {
System.out.println(i[x].iMethod()+" "+i[x].getClass());
}
}
}
So in this example class Of76 can make classes out of another file that doesn't have any public classes. I am confused on why the first file can have all those classes and why they are not in separate classes. I read that a class that is not public is private by default, and can only be called within the same class. So everything in the Nose file can only be called inside that Nose file?
When you exlude public and don't have anything else there like protected or private this is called "package protected". This should explain the differences to you: In Java, difference between default, public, protected, and private
The answer to this question is a matter of perspective.
If you are a new Java learner and you are learning language features and the object-oriented paradigm, then a reasonable answer is "you should always make classes public" because visibility restrictions matter to nobody but you. Visibility is an issue only for production code or when you are exporting an API for other clients to use. It is not unreasonable to make classes public until you know how to write good classes (I would NOT extend this advice to fields of classes, however).
However...
If you are maintaining or modifying production code -or- developing an API that you intend to export for other programmers to use, then the best answer is "you should never make classes public unless your clear intent is that your clients should be able to access your class and use it in their own client code.
Visibility is one of the most important security and encapsulation mechanisms in Java and you should never be cavalier about it in a production environment. Everything in your API should have the lowest possible visibility.
There are some important exceptions that can be imposed upon you by other API's that you may be using. For example, if you are developing a controller class for JavaFX, then in JavaFX 2.2 you are required to make your class public, whether you want to or not. Even so, these exceptions do not break the rule that "everything in your API should have the lowest possible visibility."
TL;DR: If the code you're working on will be accessed only by you, then you need never make classes anything but public. If you're working on production code, code that will become available to others, or an API that you intend to export for client use, then you should never make classes public unless it is a clearly indicated part of your design.
public MyClass this class will be visible to classes in your package and classes in other packages.
protected MyClass this class will be visible to classes in your package and only other classes that are subclasses of MyClass.
MyClass this is "default access" or "package-private" access. MyClass is visible only to classes in the same package.
private MyClass this class is not visisble to other classes except those that are in the same .class file.
Default access and Private access are considered non-exported visibility levels. Classes with these visibility levels may be freely modified by you as their implementation details are not exported as part of any API.
Public and protected access are considered exported visibility levels. Generally, once you've exported a class as part of your API you are expected to continue to support it "forever".
I'm using a Java class library that is in many ways incomplete: there are many classes that I feel ought to have additional member functions built in. However, I am unsure of the best practice of adding these member functions.
Lets call the insufficient base class A.
class A
{
public A(/*long arbitrary arguments*/)
{
//...
}
public A(/*long even more arbitrary arguments*/)
{
//...
}
public int func()
{
return 1;
}
}
Ideally, I would like to add a function to A. However, I can't do that. My choice is between:
class B extends A
{
//Implement ALL of A's constructors here
public int reallyUsefulFunction()
{
return func()+1;
}
}
and
class AddedFuncs
{
public static int reallyUsefulFunction(A a)
{
return a.func()+1;
}
}
The way I see it, they both have advantages and disadvantages. The first choice gives a cleaner syntax than the second, and is more logical, but has problems: Let's say I have a third class, C, within the class library.
class C
{
public A func()
{
return new A(/*...*/);
}
}
As I see it, there is no easy way of doing this:
C c;
int useful = c.func().reallyUsefulFunction();
as the type returned by C.func() is an A, not a B, and you can't down-cast.
So what is the best way of adding a member function to a read-only library class?
Natural and frequent dilemma. Read about the composition vs inheritance alternative. Your second alternative is basically a composition, if we think that the object A is passed in the constructor instead of passing it in each method - that is, we would be using composition to implement a wrapper or decorator pattern.
The issue for class C returning a new instance of class A has no trivial solution, as you guessed, as long as class C decides to take responsability of creating the new instance. This is why one should pause and think before typing a "new" statement inside a class, if there is the possibility that this class will be subclassed. In yout example, it would be nice if you could tell class C what concrete class to return ... but how would it know to create it? Well we could pass him an object who knows how to instantiate an object of class A (or a subclass)... I guess you are enough motivated to read about Factories now, and design patterns in general.
There is no unique best answer, but if want a quick one: I'd make a wrapper, B class does not extend A but has a constructor with A as parameter, it delegates its methods (except the own) to the inside object.
When you need to call the method in class C (I'm assuming you cant touch class C), you could write: B b = new B(c.func())
Why not use Composition instead of Inheritance?
class ABetterA {
private A a;
public ABetterA() {
}
// write wrapper methods calling class' A methods and maybe doing something more
}
This way, you could also mimic multiple inheritance...
You have a third option. You could use Scala (a Java compatible language) and its traits, which are mixins by another name.
Another option similar to Brian's sugestion is to use Aspect Oriented Programming (AOP) tool, such as ApectJ, which let you "inject" additional functionality into existing classes, even binary ones. You either preprocess the library jar to get a new one with enhanced classes ("static weaving") or you can do all of this at runtime when the library classes are loaded (so called "load-time weaving"). You can check this AspectJ example.
Even though AOP is normally used to modify existing methods (before, after or around "advices" = code pieces) you can also introduce new members and methods - check AspectJ's Inter-type declarations.
Of course there is the question whether AspectJ is supported at your limited platform.
This question already has answers here:
Java 8: Interface with static methods instead of static util class
(5 answers)
Closed 7 years ago.
For the past decade or so, I've been using the pattern below for my Java utility classes. The class contains only static methods and fields, is declared final so it can't be extended, and has a private constructor so it can't be instantiated.
public final class SomeUtilityClass {
public static final String SOME_CONSTANT = "Some constant";
private SomeUtilityClass() {}
public static Object someUtilityMethod(Object someParameter) {
/* ... */
return null;
}
}
Now, with the introduction of static methods in interfaces in Java 8, I lately find myself using a utility interface pattern:
public interface SomeUtilityInterface {
String SOME_CONSTANT = "Some constant";
static Object someUtilityMethod(Object someParameter) {
/* ... */
return null;
}
}
This allows me to get rid of the constructor, and a lot of keywords (public, static, final) that are implicit in interfaces.
Are there any downsides to this approach? Are there any benefits to using a utility class over a utility interface?
You should use interface only if you expect that somebody would implement it. For example, java.util.stream.Stream interface has a bunch of static methods which could be located in some Streams or StreamUtils class prior to Java 8. However it's a valid interface which has non-static methods as well and can be implemented. The java.util.Comparable is another example: all static methods there just support the interface. You cannot forbid users from implementing your public interface, but for utility class you can forbid them to instantiate it. Thus for the code clarity I suggest not to use interfaces unless they are intended to be implemented.
A note regarding #saka1029 answer. While it's true that you cannot define helper private methods and constants in the same interface, it's not a problem to create a package-private class in the same package like MyInterfaceHelper which will have all the necessary implementation-related stuff. In general package-private classes are good to hide your implementation details from the outer world.
Going based on the person who coined the Constant Interface pattern an anti-pattern, I would say although you don't intend the client(s) to implement the interface, it's still possible, possibly easier, and shouldn't be allowed:
APIs should be easy to use and hard to misuse. It should be easy to do simple things; possible to do complex things; and impossible, or at least difficult, to do wrong things.
Although as mentioned below, it really depends on the target audience
A lot of easy-to-use designs patterns get a lot of criticism (Context pattern, Singleton pattern, Constant Interface pattern). Heck, even design principles such as the law of demeter gets criticised for being too verbose.
I'd hate to say it, but these kinds of decisions are opinion based. Although the context pattern is seen as an anti-pattern, it's apparent in mainstream frameworks such as Spring and the Android SDK. It boils down to the environment, as well as target audience.
The main downside that I can find is listed as the third listing under "downsides" in the Constant Interface wiki:
If binary code compatibility is required in future releases, the constants interface must remain forever an interface (it cannot be converted into a class), even though it has not been used as an interface in the conventional sense.
If you ever figure "Hey, this actually isn't a contract and I want to enforce stronger design", you will not be able to change it. But as I've said, it's up to you; maybe you won't care to change it in the future.
On top of that, code clarity as mentioned by #TagirValeev. Interfaces have the intent of being implemented; if you don't want someone to implement the API you're supplying, don't make it implementable. But I believe this revolves around the "target audience" statement. Not gonna lie, I'm with you on the less-verbose foundation, but it depends on who my code is for; wouldn't wanna use a constant interface for code that may get reviewed.
You should not use interface.
Interfaces cannot have private constants and static initializers.
public class Utility {
private Utility() {}
public static final Map<String, Integer> MAP_CONSTANT;
static {
Map<String, Integer> map = new HashMap<>();
map.put("zero", 0);
map.put("one", 1);
map.put("three", 3);
MAP_CONSTANT = Collections.unmodifiableMap(map);
}
private static String PRIVATE_CONSTANT = "Hello, ";
public static String hello(String name) {
return PRIVATE_CONSTANT + name;
}
}
I think it would work. I think the variable SOME_CONSTANT defaults to being static final in your SomeUtilityInterface, even though you didn't explicitly say so. So, it would work as a Utility but wouldn't you have some mutability problems that you wouldn't have with a regular class with all member variables being required to be final? As long as thats not an issue with your particular implementation of the default methods, I can't think of a problem.