Is there some object oriented thing that you can call some methods from certain classes, but not all of them? Is there something like that which is similiar to protected
?
Say you have a method void foo()
and you want it to be available to the programmer in a few types of classes (perhaps something like using Type variables (to specify: T type
). Now, perhaps is there some way, without inheriting the class with foo()
in it, or making an interface, to specify which classes or types of classes have access to that method?
I would guess this could be like multiple-inheritance and polymorphism? But I still want only the class and certain classes to access the method without changing the visibility of the method. I want the visibility to be class-specific.
Here is an example:
class A
sees foo()
as private, but only that class sees it as private.
class B
sees foo()
as public/protected, but only that class sees it as public.
The method type would be default
.
I guess what is easier to ask and answer to is: "Is there class-specific visibility?"
No, there's nothing like that in Java.
The closest you've got is putting classes within the same package, at which point they have access to any members which don't specify any access modifier. You can't specify particular classes though.
Another option which is appropriate in some cases is to use nested classes:
class Outer {
private static class Inner {
}
}
Here Outer
and Inner
have access to each other's private members.
See more on this question at Stackoverflow