I am learning Java Programming and I am a beginner. I am learning Interfaces now. I came across the below two simple examples and I have doubt in those
Program1
public interface Callback {
void callback(int param);
}
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
// c.nonIfaceMeth();
}
}
Program 2
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
class TestIface {
public static void main(String args[]) {
Client c = new Client();
c.callback(42);
}
}
Both Program1 and Program2 give the same output.
In Program1, variable c is declared to be of the interface type and in Program2, variable c is declared to be of the Class type.
My doubt is what is the difference between these two programs and what are the advantages of creating a Interface type variable ?
Kindly help me t understand the concept. TIA
I will try to keep it short as web is full explainaions on interfaces.
Interface is a contract. Many classes can implement an interface. Using interface is one way to loosly couple your code components.
In Program1, variable c is declared to be of the interface type
This means that any implementation of this interface can be taken to create a concrete object and your code should not break.
and in Program2, variable c is declared to be of the Class type.
This means that you have to change your code to use right class every time you need to use a different implementation. Your code is very cohesive.
It will make more sense when you start studing things like dependency injection or factory pattern etc. Also helpful in unit testing.
UPDATE
Based on your comment
I want the difference between these two statements "Callback c = new
Client();" and "Client c = new Client();"
It is very conceptual at the moment but Callback c = new Client() but allows you to change the type of your varible Cat any time. Lets say there is an other implementation ImportantClient in your code where interface is used to declare the variable you can at any time change it to c = new ImportantClient(). However you can not do that if you are using Client c = new Client();
Both are same in your case when saying
Client c = new Client();
Here actually you are just creating an object of a client. And calling a method of the class Client.
And when you say
Callback c = new Client();
You are just creating a reference of type CallBack but at runtime an Object of Client is being created. So both are same in your case.
In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle {
// wheel revolutions per minute
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
Reference : Oracle JAVA Documentation
Go through : Using an Interface as a Type
One reason to use an interface is when you want to reduce dependencies between classes or components.
If you have a method that can take an interface as a parameter, for example:
public int countItems(List myList) { ... }
... then you are able to pass in any object whose class implements the List interface, without have that dependency hard coded in the method.
In your case, using the interface Callback enables other classes to be used in the code, if they implement the Callback interface.
Another reason is that it buys you flexibility in choice of concrete class. If you create the object and keep a reference to the interface, it restricts you to only interact with the object through the interface's methods. This means that in future, you could change which concrete class you construct, and as long as it implements the interface, your code will continue to work without requiring modification.
Related
I have a software specification document for a specific library in java which helps collecting data from a biosensor and has a class called 'Patch'. The document specifies:
Following is the constructor of Patch class:
Patch(JSONObject options, (JSONObject)->onDiscovery,(JSONObject)->ondata,(JSONObject)->onStatus)
Where
JOSNObject options: options settings for the object
(JSONObject)->onDiscovery: Callback for receiving the sensor info as a JSONObject,
(JSONObject)->ondata: Callback for receiving the sensor data as a JSONObject,
(JSONObject)->onStatus: Callback for receiving the global errors as a JSONObject
It should be called as
Patch patch=newPatch(jsonConfigObject, discoveryObject, streamObject, status);
The concerned fellow stated that these callbacks shall be just lambda expressions.
Now what I understand is:
Constructor takes 4 args:
An empty JSON object,
Callback function reference
Callback function reference
Callback function reference
Am new to Callback implementation so am not able to figure out:
how shall I implement this one in my code?
Do I have to create the functional interfaces for each of those callback methods?
Lets say I have just imported the library, what shall I do next?
The objective of lambda expressions is to denote methods that the Patch-object can call (back) at certain events. In contrast to other programming languages it was not possible to pass functions as parameters to constructors or methods in Java. Thus it was necessary to create an object of a class that implements a certain interface (or is otherwise known to have a certain method by type) and to pass it to the method or constructor as a parameter. The method can then be called at the passed object when the event occurs.
The functional interface is already there. You do not need to create it by yourself. It has been already used in the signature of the constructor of Patch (the types of the last three parameters to the constructor). Functional interfaces are types which have exactly one abstract method that has to be overridden.
Lets suppose the functional interface looks like this:
interface Callback { // could of course have a different name
public void call(JSONObject o);
}
It is not necessary to add the #FunctionalInterface-annotation. It would only prevent the interface from later modifications, namely adding further abstract methods.
It seems reasonable to assume that the abstract method does not have a return value (but you need to check this. When you use lambda expressions you do not need to know what the actual method name (here call) is.
Although most handy it is not necessary to call the constructor with lambda expressions for the last three parameters. Other possibilities include a method reference (using ::), anonymous classes, and instantiating a newly defines class.
Of course you need to know what should happen when the three events occur. Lets say that you have already three methods that provide the necessary functionality. Probably a JSONObject that contains information about the event is necessary to do something useful.
class Main {
static void onDiscovery(JSONObject o) {...}
static void onData(JSONObject o) {...}
static void onStatus(JSONObject o) {...}
}
It is not necessary that the three methods have exactly these names nor that they are static.
In the main method of this class (or somewhere else) could happen:
public static void main(String[] args) {
JSONObject o = // ...
Patch p = new Patch(o,
(x) -> Main.onDiscovery(x), // (1) lambda expr. (Main. can be omitted)
Main::onData, // (2) method reference
new Callback() { // (3) anonymous inner class
public void call(JSONObject x) {
Main.onStatus(x);
}
});
//...
}
(1)-(3) show alternative ways to pass an object of type Callback.
(1) has the advantage that shorter implementations could go right here instead of calling onDiscovery(x). If you have more than one statement you need curly brackets around the statements and ";" after each statement:
(x) -> {
System.out.println("discovery event");
System.out.println(x.getXYZ());
// ...
}
(2) has the advantage to be super concise. If you do not have a static method to reference, a object reference can also be used to denote the object on which the method should be called.
(3) anonymous inner classes are would normally not be used anymore for functional interfaces. If the interface / abstract class has more abstract methods but one it is still necessary to use anonymous inner classes.
class Main {
void onData(JSONObject o) { ... }
// ...
public static void main(String[] args) {
var m = new Main();
var o = new JSONObject(); // or whatever
var p = new Patch(o,
(x) -> m.onDiscovery(x),
m::onData;
new Callback() {
public void call(JSONObject x) {
m.onStatus(x);
}
});
}
}
This is something I ran into trying to solve someone else's question here, in a simplified version. Client and Server with reflexive (circular) dependency use generics to try to keep strongly typed references in super class. The wish was for arbitrary sub-type parings such as ClientType1<->ServerType2 , and for strongly typed calls on specialized methods found only in a specific type.
This only works for one level of depth: from server to client, but fails if you then try to continue from that client back to the server:
Is there any syntax which would allow arbitrary levels of strongly typed calls?
abstract class ServerBase<C extends ClientBase<?>>
{
ArrayList<C> clients = new ArrayList<C>();
}
abstract class ClientBase<S extends ServerBase<?>>
{
S server;
}
class ClientType1<S extends ServerBase<?>> extends ClientBase<S>
{
public void clientType1Method() {}
}
class ServerType1<C extends ClientBase<?>> extends ServerBase<C>
{
}
public class Example {
public static void main(String[] args) {
ServerType1<ClientType1<?>> s = new ServerType1<>();
s.clients.get(0).clientType1Method(); // Single depth level - OK
s.clients.get(0).server.clients.get(0).clientType1Method(); // level 2 - compiler error - undefined method
}
}
In my opinion you should not actually need such an intricate reference.
What you really mean is that the client has to hold a reference to a server it can connect, and viceversa.
what should work is:
abstract class ServerBase<C extends ClientBase<? extends ServerBase>>
{
ArrayList<C> clients = new ArrayList<C>();
}
abstract class ClientBase<S extends ServerBase<? extends ClientBase>>
{
S server;
}
If you do a small tweak with this code it will surely work.
abstract class ClientBase<S extends ServerBase<?>> {
S server;
public abstract void clientMethod();
}
.......
public static void main(String[] args) {
ServerType1<ClientBase<?>> s = new ServerType1<>();
s.clients.get(0).clientMethod(); // Single depth level - OK
s.clients.get(0).server.clients.get(0).clientMethod();
// second level - NO compiler error
}
Well, it fails because you have entered yourself a ? instead of an actual type. If you use
ServerType1<ClientType1<ServerType1<ClientType1<?>>>> s = new ServerType1<>();
s.clients.get(0).clientType1Method();
s.clients.get(0).server.clients.get(0).clientType1Method();
instead, it will work. Though it is quite pointless, if we assume that s.clients.get(0).server is the same as s.
Having a circular dependency works only, if you have named types you can refer to, e.g.
public static <S extends ServerType1<ClientType1<S>>> void main(String[] args) {
ServerType1<ClientType1<S>> s = new ServerType1<>();
s.clients.get(0).clientType1Method();
s.clients.get(0).server.clients.get(0).clientType1Method();
s.clients.get(0).server.clients.get(0).server.clients.get(0).clientType1Method();
s.clients.get(0).server.clients.get(0).server.clients.get(0)
.server.clients.get(0).clientType1Method();
s.clients.get(0).server.clients.get(0).server.clients.get(0)
.server.clients.get(0).server.clients.get(0).clientType1Method();
}
Though this is likely to be impractical for most use cases. As soon as you end up having to instantiate S, you would need a real class instead. You should rethink whether you really need such a generic construct. And if you really consider creating such code with helper type variables that are irrelevant to the method’s caller, you should do that with private methods, to avoid them being visible in the public API of your class.
This may be something common and trivial, but I seem to be having trouble finding a concrete answer. In C# there is a concept of delegates, which relates strongly to the idea of function pointers from C++. Is there a similar functionality in Java? Given that pointers are somewhat absent, what is the best way about this? And to be clear, we're talking first class here.
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
and method references:
list.sort(MyClass::isGreaterThan);
You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.
public interface IFunction {
public void execute(Object o);
}
This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
As an example say we have a collection of numbers and you would like to add 1 to every element.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
You can use reflection to do it.
Pass as parameter the object and the method name (as a string) and then invoke the method. For example:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
And then use it as in:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
Of course, check all exceptions and add the needed casts.
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.
To achieve similar functionality you could use anonymous inner classes.
If you were to define a interface Foo:
interface Foo {
Object myFunc(Object arg);
}
Create a method bar which will receive a 'function pointer' as an argument:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Finally call the method as follows:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}
Java8 has introduced lambdas and method references. So if your function matches a functional interface (you can create your own) you can use a method reference in this case.
Java provides a set of common functional interfaces. whereas you could do the following:
public class Test {
public void test1(Integer i) {}
public void test2(Integer i) {}
public void consumer(Consumer<Integer> a) {
a.accept(10);
}
public void provideConsumer() {
consumer(this::test1); // method reference
consumer(x -> test2(x)); // lambda
}
}
There is no such thing in Java. You will need to wrap your function into some object and pass the reference to that object in order to pass the reference to the method on that object.
Syntactically, this can be eased to a certain extent by using anonymous classes defined in-place or anonymous classes defined as member variables of the class.
Example:
class MyComponent extends JPanel {
private JButton button;
public MyComponent() {
button = new JButton("click me");
button.addActionListener(buttonAction);
add(button);
}
private ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle the event...
// note how the handler instance can access
// members of the surrounding class
button.setText("you clicked me");
}
}
}
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
We have a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array did not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to it's inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:
http://code.google.com/p/lambdaj/wiki/Closures
Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.
/*Just to merge functions in a common name*/
public class CustomFunction{
public CustomFunction(){}
}
/*Actual functions*/
public class Function1 extends CustomFunction{
public Function1(){}
public void execute(){...something here...}
}
public class Function2 extends CustomFunction{
public Function2(){}
public void execute(){...something here...}
}
.....
/*in Main class*/
CustomFunction functionpointer = null;
then depending on the application, assign
functionpointer = new Function1();
functionpointer = new Function2();
etc.
and call by
functionpointer.execute();
Example:
public class TestClass {
public static void main(String[] args) {
TestClass t = new TestClass();
}
private static void testMethod() {
abstract class TestMethod {
int a;
int b;
int c;
abstract void implementMe();
}
class DummyClass extends TestMethod {
void implementMe() {}
}
DummyClass dummy = new DummyClass();
}
}
I found out that the above piece of code is perfectly legal in Java. I have the following questions.
What is the use of ever having a class definition inside a method?
Will a class file be generated for DummyClass
It's hard for me to imagine this concept in an Object Oriented manner. Having a class definition inside a behavior. Probably can someone tell me with equivalent real world examples.
Abstract classes inside a method sounds a bit crazy to me. But no interfaces allowed. Is there any reason behind this?
This is called a local class.
2 is the easy one: yes, a class file will be generated.
1 and 3 are kind of the same question. You would use a local class where you never need to instantiate one or know about implementation details anywhere but in one method.
A typical use would be to create a throw-away implementation of some interface. For example you'll often see something like this:
//within some method
taskExecutor.execute( new Runnable() {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
});
If you needed to create a bunch of these and do something with them, you might change this to
//within some method
class myFirstRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
}
class mySecondRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomethingElse( parameter );
}
}
taskExecutor.execute(new myFirstRunnableClass());
taskExecutor.execute(new mySecondRunnableClass());
Regarding interfaces: I'm not sure if there's a technical issue that makes locally-defined interfaces a problem for the compiler, but even if there isn't, they wouldn't add any value. If a local class that implements a local interface were used outside the method, the interface would be meaningless. And if a local class was only going to be used inside the method, both the interface and the class would be implemented within that method, so the interface definition would be redundant.
Those are called local classes. You can find a detailed explanation and an example here. The example returns a specific implementation which we doesn't need to know about outside the method.
The class can't be seen (i.e. instantiated, its methods accessed without Reflection) from outside the method. Also, it can access the local variables defined in testMethod(), but before the class definition.
I actually thought: "No such file will be written." until I just tried it: Oh yes, such a file is created! It will be called something like A$1B.class, where A is the outer class, and B is the local class.
Especially for callback functions (event handlers in GUIs, like onClick() when a Button is clicked etc.), it's quite usual to use "anonymous classes" - first of all because you can end up with a lot of them. But sometimes anonymous classes aren't good enough - especially, you can't define a constructor on them. In these cases, these method local classes can be a good alternative.
The real purpose of this is to allow us to create classes inline in function calls to console those of us who like to pretend that we're writing in a functional language ;)
The only case when you would like to have a full blown function inner class vs anonymous class ( a.k.a. Java closure ) is when the following conditions are met
you need to supply an interface or abstract class implementation
you want to use some final parameters defined in calling function
you need to record some state of execution of the interface call.
E.g. somebody wants a Runnable and you want to record when the execution has started and ended.
With anonymous class it is not possible to do, with inner class you can do this.
Here is an example do demonstrate my point
private static void testMethod (
final Object param1,
final Object param2
)
{
class RunnableWithStartAndEnd extends Runnable{
Date start;
Date end;
public void run () {
start = new Date( );
try
{
evalParam1( param1 );
evalParam2( param2 );
...
}
finally
{
end = new Date( );
}
}
}
final RunnableWithStartAndEnd runnable = new RunnableWithStartAndEnd( );
final Thread thread = new Thread( runnable );
thread.start( );
thread.join( );
System.out.println( runnable.start );
System.out.println( runnable.end );
}
Before using this pattern though, please evaluate if plain old top-level class, or inner class, or static inner class are better alternatives.
The main reason to define inner classes (within a method or a class) is to deal with accessibility of members and variables of the enclosing class and method.
An inner class can look up private data members and operate on them. If within a method it can deal with final local variable as well.
Having inner classes does help in making sure this class is not accessible to outside world. This holds true especially for cases of UI programming in GWT or GXT etc where JS generating code is written in java and behavior for each button or event has to be defined by creating anonymous classes
I've came across a good example in the Spring. The framework is using concept of local class definitions inside of the method to deal with various database operations in a uniform way.
Assume you have a code like this:
JdbcTemplate jdbcOperations = new JdbcTemplate(this.myDataSource);
jdbcOperations.execute("call my_stored_procedure()")
jdbcOperations.query(queryToRun, new MyCustomRowMapper(), withInputParams);
jdbcOperations.update(queryToRun, withInputParams);
Let's first look at the implementation of the execute():
#Override
public void execute(final String sql) throws DataAccessException {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL statement [" + sql + "]");
}
/**
* Callback to execute the statement.
(can access method local state like sql input parameter)
*/
class ExecuteStatementCallback implements StatementCallback<Object>, SqlProvider {
#Override
#Nullable
public Object doInStatement(Statement stmt) throws SQLException {
stmt.execute(sql);
return null;
}
#Override
public String getSql() {
return sql;
}
}
//transforms method input into a functional Object
execute(new ExecuteStatementCallback());
}
Please note the last line. Spring does this exact "trick" for the rest of the methods as well:
//uses local class QueryStatementCallback implements StatementCallback<T>, SqlProvider
jdbcOperations.query(...)
//uses local class UpdateStatementCallback implements StatementCallback<Integer>, SqlProvider
jdbcOperations.update(...)
The "trick" with local classes allows the framework to deal with all of those scenarios in a single method which accept those classes via StatementCallback interface.
This single method acts as a bridge between actions (execute, update) and common operations around them (e.g execution, connection management, error translation and dbms console output)
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
//
T result = action.doInStatement(stmt);
handleWarnings(stmt);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallback", sql, ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
Everything is clear here but I wanted to place another example of reasonable use case for this definition type of class for the next readers.
Regarding #jacob-mattison 's answer, If we assume we have some common actions in these throw-away implementations of the interface, So, it's better to write it once but keep the implementations anonymous too:
//within some method
abstract class myRunnableClass implements Runnable {
protected abstract void DO_AN_SPECIFIC_JOB();
public void run() {
someCommonCode();
//...
DO_AN_SPECIFIC_JOB();
//..
anotherCommonCode();
}
}
Then it's easy to use this defined class and just implement the specific task separately:
taskExecutor.execute(new myRunnableClass() {
protected void DO_AN_SPECIFIC_JOB() {
// Do something
}
});
taskExecutor.execute(new myRunnableClass() {
protected void DO_AN_SPECIFIC_JOB() {
// Do another thing
}
});
I know that an interface must be public. However, I don't want that.
I want my implemented methods to only be accessible from their own package, so I want my implemented methods to be protected.
The problem is I can't make the interface or the implemented methods protected.
What is a work around? Is there a design pattern that pertains to this problem?
From the Java guide, an abstract class wouldn't do the job either.
read this.
"The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface."
Is that what you want?
You class can use package protection and still implement an interface:
class Foo implements Runnable
{
public void run()
{
}
}
If you want some methods to be protected / package and others not, it sounds like your classes have more than one responsibility, and should be split into multiple.
Edit after reading comments to this and other responses:
If your are somehow thinking that the visibility of a method affects the ability to invoke that method, think again. Without going to extremes, you cannot prevent someone from using reflection to identify your class' methods and invoke them. However, this is a non-issue: unless someone is trying to crack your code, they're not going to invoke random methods.
Instead, think of private / protected methods as defining a contract for subclasses, and use interfaces to define the contract with the outside world.
Oh, and to the person who decided my example should use K&R bracing: if it's specified in the Terms of Service, sure. Otherwise, can't you find anything better to do with your time?
When I have butted up against this I use a package accessible inner or nested class to implement the interface, pushing the implemented method out of the public class.
Usually it's because I have a class with a specific public API which must implement something else to get it's job done (quite often because the something else was a callback disguised as an interface <grin>) - this happens a lot with things like Comparable. I don't want the public API polluted with the (forced public) interface implementation.
Hope this helps.
Also, if you truly want the methods accessed only by the package, you don't want the protected scope specifier, you want the default (omitted) scope specifier. Using protected will, of course, allow subclasses to see the methods.
BTW, I think that the reason interface methods are inferred to be public is because it is very much the exception to have an interface which is only implemented by classes in the same package; they are very much most often invoked by something in another package, which means they need to be public.
This question is based on a wrong statement:
I know that an interface must be public
Not really, you can have interfaces with default access modifier.
The problem is I can't make the interface or the implemented methods protected
Here it is:
C:\oreyes\cosas\java\interfaces>type a\*.java
a\Inter.java
package a;
interface Inter {
public void face();
}
a\Face.java
package a;
class Face implements Inter {
public void face() {
System.out.println( "face" );
}
}
C:\oreyes\cosas\java\interfaces>type b\*.java
b\Test.java
package b;
import a.Inter;
import a.Face;
public class Test {
public static void main( String [] args ) {
Inter inter = new Face();
inter.face();
}
}
C:\oreyes\cosas\java\interfaces>javac -d . a\*.java b\Test.java
b\Test.java:2: a.Inter is not public in a; cannot be accessed from outside package
import a.Inter;
^
b\Test.java:3: a.Face is not public in a; cannot be accessed from outside package
import a.Face;
^
b\Test.java:7: cannot find symbol
symbol : class Inter
location: class b.Test
Inter inter = new Face();
^
b\Test.java:7: cannot find symbol
symbol : class Face
location: class b.Test
Inter inter = new Face();
^
4 errors
C:\oreyes\cosas\java\interfaces>
Hence, achieving what you wanted, prevent interface and class usage outside of the package.
Here's how it could be done using abstract classes.
The only inconvenient is that it makes you "subclass".
As per the java guide, you should follow that advice "most" of the times, but I think in this situation it will be ok.
public abstract class Ab {
protected abstract void method();
abstract void otherMethod();
public static void main( String [] args ) {
Ab a = new AbImpl();
a.method();
a.otherMethod();
}
}
class AbImpl extends Ab {
protected void method(){
System.out.println( "method invoked from: " + this.getClass().getName() );
}
void otherMethod(){
System.out.println("This time \"default\" access from: " + this.getClass().getName() );
}
}
Here's another solution, inspired by the C++ Pimpl idiom.
If you want to implement an interface, but don't want that implementation to be public, you can create a composed object of an anonymous inner class that implements the interface.
Here's an example. Let's say you have this interface:
public interface Iface {
public void doSomething();
}
You create an object of the Iface type, and put your implementation in there:
public class IfaceUser {
private int someValue;
// Here's our implementor
private Iface impl = new Iface() {
public void doSomething() {
someValue++;
}
};
}
Whenever you need to invoke doSomething(), you invoke it on your composed impl object.
I just came across this trying to build a protected method with the intention of it only being used in a test case. I wanted to delete test data that I had stuffed into a DB table. In any case I was inspired by #Karl Giesing's post. Unfortunately it did not work. I did figure a way to make it work using a protected inner class.
The interface:
package foo;
interface SomeProtectedFoo {
int doSomeFoo();
}
Then the inner class defined as protected in public class:
package foo;
public class MyFoo implements SomePublicFoo {
// public stuff
protected class ProtectedFoo implements SomeProtectedFoo {
public int doSomeFoo() { ... }
}
protected ProtectedFoo pFoo;
protected ProtectedFoo gimmeFoo() {
return new ProtectedFoo();
}
}
You can then access the protected method only from other classes in the same package, as my test code was as show:
package foo;
public class FooTest {
MyFoo myFoo = new MyFoo();
void doProtectedFoo() {
myFoo.pFoo = myFoo.gimmeFoo();
myFoo.pFoo.doSomeFoo();
}
}
A little late for the original poster, but hey, I just found it. :D
You can go with encapsulation instead of inheritance.
That is, create your class (which won't inherit anything) and in it, have an instance of the object you want to extend.
Then you can expose only what you want.
The obvious disadvantage of this is that you must explicitly pass-through methods for everything you want exposed. And it won't be a subclass...
I would just create an abstract class. There is no harm in it.
With an interface you want to define methods that can be exposed by a variety of implementing classes.
Having an interface with protected methods just wouldn't serve that purpose.
I am guessing your problem can be solved by redesigning your class hierarchy.
One way to get around this is (depending on the situation) to just make an anonymous inner class that implements the interface that has protected or private scope. For example:
public class Foo {
interface Callback {
void hiddenMethod();
}
public Foo(Callback callback) {
}
}
Then in the user of Foo:
public class Bar {
private Foo.Callback callback = new Foo.Callback() {
#Override public void hiddenMethod() { ... }
};
private Foo foo = new Foo(callback);
}
This saves you from having the following:
public class Bar implements Foo.Callback {
private Foo foo = new Foo(this);
// uh-oh! the method is public!
#Override public void hiddenMethod() { ... }
}
I think u can use it now with Java 9 release. From the openJdk notes for Java 9,
Support for private methods in interfaces was briefly in consideration
for inclusion in Java SE 8 as part of the effort to add support for
Lambda Expressions, but was withdrawn to enable better focus on higher
priority tasks for Java SE 8. It is now proposed that support for
private interface methods be undertaken thereby enabling non abstract
methods of an interface to share code between them.
refer https://bugs.openjdk.java.net/browse/JDK-8071453