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
Related
Just as a counterpoint to this question: what is an interface in Java?
An interface is a special form of an abstract class which does not implement any methods. In Java, you create an interface like this:
interface Interface
{
void interfaceMethod();
}
Since the interface can't implement any methods, it's implied that the entire thing, including all the methods, are both public and abstract (abstract in Java terms means "not implemented by this class"). So the interface above is identical to the interface below:
public interface Interface
{
abstract public void interfaceMethod();
}
To use this interface, you simply need to implement the interface. Many classes can implement an interface, and a class can implement many interfaces:
interface InterfaceA
{
void interfaceMethodA();
}
interface InterfaceB
{
void interfaceMethodB();
}
public class ImplementingClassA
implements InterfaceA, InterfaceB
{
public void interfaceMethodA()
{
System.out.println("interfaceA, interfaceMethodA, implementation A");
}
public void interfaceMethodB()
{
System.out.println("interfaceB, interfaceMethodB, implementation A");
}
}
public class ImplementingClassB
implements InterfaceA, InterfaceB
{
public void interfaceMethodA()
{
System.out.println("interfaceA, interfaceMethodA, implementation B");
}
public void interfaceMethodB()
{
System.out.println("interfaceB, interfaceMethodB, implementation B");
}
}
Now if you wanted you could write a method like this:
public void testInterfaces()
{
ImplementingClassA u = new ImplementingClassA();
ImplementingClassB v = new ImplementingClassB();
InterfaceA w = new ImplementingClassA();
InterfaceA x = new ImplementingClassB();
InterfaceB y = new ImplementingClassA();
InterfaceB z = new ImplementingClassB();
u.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation A"
u.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation A"
v.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation B"
v.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation B"
w.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation A"
x.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation B"
y.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation A"
z.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation B"
}
However, you could never do the following:
public void testInterfaces()
{
InterfaceA y = new ImplementingClassA();
InterfaceB z = new ImplementingClassB();
y.interfaceMethodB(); // ERROR!
z.interfaceMethodA(); // ERROR!
}
The reason you can't do this is that y is of type interfaceA, and there is no interfaceMethodB() in interfaceA. Likewise, z is of type interfaceB and there is no interfaceMethodA() in interfaceB.
I mentioned earlier that interfaces are just a special form of an abstract class. To illustrate that point, look at the following code.
interface Interface
{
void abstractMethod();
}
abstract public class AbstractClass
{
abstract public void abstractMethod();
}
You would inherit from these classes almost exactly the same way:
public class InheritsFromInterface
implements Interface
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}
public class InteritsFromAbstractClass
extends AbstractClass
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}
In fact, you could even change the interface and the abstract class like this:
interface Interface
{
void abstractMethod();
}
abstract public class AbstractClass
implements Interface
{
abstract public void abstractMethod();
}
public class InheritsFromInterfaceAndAbstractClass
extends AbstractClass implements Interface
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}
However, there are two differences between interfaces and abstract classes.
The first difference is that interfaces cannot implement methods.
interface Interface
{
public void implementedMethod()
{
System.out.println("implementedMethod()");
}
}
The interface above generates a compiler error because it has an implementation for implementedMethod(). If you wanted to implement the method but not be able to instantiate the class, you would have to do it like this:
abstract public class AbstractClass
{
public void implementedMethod()
{
System.out.println("implementedMethod()");
}
}
That's not much of an abstract class because none of its members are abstract, but it is legal Java.
The other difference between interfaces and abstract classes is that a class can inherit from multiple interfaces, but can only inherit from one abstract class.
abstract public class AbstractClassA { }
abstract public class AbstractClassB { }
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }
The code above generates a compiler error, not because the classes are all empty, but because InheritsFromTwoAbstractClasses is trying to inherit from two abstract classes, which is illegal. The following is perfectly legal.
interface InterfaceA { }
interface InterfaceB { }
public class InheritsFromTwoInterfaces
implements InterfaceA, InterfaceB
{ }
The first difference between interfaces and abstract classes is the reason for the second difference. Take a look at the following code.
interface InterfaceA
{
void method();
}
interface InterfaceB
{
void method();
}
public class InheritsFromTwoInterfaces
implements InterfaceA, InterfaceB
{
void method() { System.out.println("method()"); }
}
There's no problem with the code above because InterfaceA and InterfaceB don't have anything to hide. It's easy to tell that a call to method will print "method()".
Now look at the following code:
abstract public class AbstractClassA
{
void method() { System.out.println("Hello"); }
}
abstract public class AbstractClassB
{
void method() { System.out.println("Goodbye"); }
}
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }
This is exactly the same as our other example, except that because we're allowed to implement methods in abstract classes, we did, and because we don't have to implement already-implemented methods in an inheriting class, we didn't. But you may have noticed, there's a problem. What happens when we call new InheritsFromTwoAbstractClasses().method()? Does it print "Hello" or "Goodbye"? You probably don't know, and neither does the Java compiler. Another language, C++ allowed this kind of inheritance and they resolved these issues in ways that were often very complicated. To avoid this kind of trouble, Java decided to make this "multiple inheritance" illegal.
The downside to Java's solution that the following can't be done:
abstract public class AbstractClassA
{
void hi() { System.out.println("Hello"); }
}
abstract public class AbstractClassB
{
void bye() { System.out.println("Goodbye"); }
}
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }
AbstractClassA and AbstractClassB are "mixins" or classes that aren't intended to be instantiated but add functionality to the classes that they are "mixed into" through inheritance. There's obviously no problem figuring out what happens if you call new InheritsFromTwoAbstractClasses().hi() or new InheritsFromTwoAbstractClasses().bye(), but you can't do that because Java doesn't allow it.
(I know this is a long post, so if there are any mistakes in it please let me know and I will correct them.)
Interface is a contract. A simple example is a Tenant and Landlord which are the two parties and the contract is the Rent Agreement. Rent Agreement contains various clause which Tenants have to follow. Likewise Interface is a contact which contains various method (Declaration) which the Party has to implement (provide method bodies).Here party one is the class which implement the interface and second party is Client and the way to use and interface is having “Reference of Interface” and “Object of Implementing class”: below are 3 components:(Explained with help of example)
Component 1] Interface : The Contract
interface myInterface{
public void myMethod();
}
Component 2] Implementing Class : Party number 1
class myClass implements myInterface {
#Override
public void myMethod() {
System.out.println("in MyMethod");
}
}
Component 3] Client code : Party number 2
Client.java
public class Client {
public static void main(String[] args) {
myInterface mi = new myClass();
// Reference of Interface = Object of Implementing Class
mi.myMethod(); // this will print in MyMethod
}
}
An interface in java is a blueprint of a class. It has static constants and abstract methods only.The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java. An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors(Abstract Methods) that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.Since multiple inheritance is not allowed in java so interface is only way to implement multiple inheritance.
Here is an example for understanding interface
interface Printable{
void print();
}
interface Showable{
void print();
}
class testinterface1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
testinterface1 obj = new testinterface1();
obj.print();
}
}
Interface : System requirement service.
Description : Suppose a client needed some functionality "i.e. JDBC API" interface and some other server Apache , Jetty , WebServer they all provide implements of this.
So it bounded requirement document which service provider provided to the user who uses data-connection with these server Apache , Jetty , WebServer .
Interface is the blueprint of an class.
There is one oop's concept called Data abstraction under that there are two categories one is abstract class and other one is interface.
Abstract class achieves only partial abstraction but interface achieves full abstraction.
In interface there is only abstract methods and final variables..you can extends any number of interface and you can implement any number of classes.
If any class is implementing the interface then the class must implements the abstract methods too
Interface cannot be instantiated.
interface A() {
void print()
}
This question is 6 years old and lot of things have changed the definition of interface over the years.
From oracle documentation page ( post Java 8 release) :
In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
Have a look at related SE questions for better explanation:
Is there more to an interface than having the correct methods
What is the difference between an interface and abstract class?
What it is
An interface is a reference type, just like a class is. These are the two main reference types in Java.
What it contains
An interface can contain a subset of what a normal class can contain. This includes everything that is static, both methods and variables, and non-static method declarations. It is not allowed to have non-static variables.
A declaration of a method differs from a normal method in several things; here is one as an example:
[public] [abstract] ReturnType methodName();
These declarations can be marked as public and abstract, as represented with [optional braces]. It is not necessary to do so, as it is the default. private, protected, package-private (aka. nothing) and the final modifier are not allowed and marked as a compiler error. They have not implementation, so there is a semicolon instead of curly braces.
As of Java 8, they can hold non-static methods with an implementation, these have to be marked with the default modifier. However, the same restrictions as to the other modifiers apply (adding that strictfp is now valid and abstract is no more).
What it's useful for
One of its uses is for it to be used as a face for a service. When two parties work together to form a service-requester & service-provider kind of relationship, the service provider provides the face of the service (as to what the service looks like) in the form of an interface.
One of the OOP concept is "Abstraction" which means to hide away complex working of the systems and show only what is necessary to understand the system. This helps in visualizing the working of a complex system.
This can be achieved through interface where in each module is visualized (and also implemented) to work through interface of another module
An interface is a class-like construct that contains only constants and abstract methods (Introduction to java programming, n.d.). Moreover, it can extend more than one interface for example a Superclass. Java allows only single inheritance for class extension but allows multiple extensions for
interfaces(Introduction to Java programming, n.d.) For example,
public class NewClass extends BaseClass
implements Interface1, ..., InterfaceN {
...
}
Secondly, interfaces can be used to specify the behavior of objects in a class. However, they cannot contain abstract methods. Also, an interface can inherit other interfaces using the extends keyword.
public interface NewInterface extends Interface1, ... , InterfaceN {
}
Reference
Introduction to Java Programming. Interfaces and Abstract classes (n.d). Retrieved March 10, 2017 from https://viewer.gcu.edu/7NNUKW
In general, we prefer interfaces when there are two are more implementations we have. Where Interface is acts as protocol.
Coding to interface, not implementations Coding to interface makes loosely couple.
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. for more details
From the latest definition by Oracle, Interface is:
There are a number of situations in software engineering when it is
important for disparate groups of programmers to agree to a "contract"
that spells out how their software interacts. Each group should be
able to write their code without any knowledge of how the other
group's code is written. Generally speaking, interfaces are such
contracts.
For example, imagine a futuristic society where computer-controlled
robotic cars transport passengers through city streets without a human
operator. Automobile manufacturers write software (Java, of course)
that operates the automobile—stop, start, accelerate, turn left, and
so forth. Another industrial group, electronic guidance instrument
manufacturers, make computer systems that receive GPS (Global
Positioning System) position data and wireless transmission of traffic
conditions and use that information to drive the car.
The auto manufacturers must publish an industry-standard interface
that spells out in detail what methods can be invoked to make the car
move (any car, from any manufacturer). The guidance manufacturers can
then write software that invokes the methods described in the
interface to command the car. Neither industrial group needs to know
how the other group's software is implemented. In fact, each group
considers its software highly proprietary and reserves the right to
modify it at any time, as long as it continues to adhere to the
published interface.
[...] An interface is a reference type, similar to a class, that can
contain only constants, method signatures, default methods, static
methods, and nested types. Method bodies exist only for default
methods and static methods. Interfaces cannot be instantiated—they
can only be implemented by classes or extended by other interfaces.
The most popular usage of interfaces is as APIs (Application Programming Interface) which are common in commercial software products. Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product.
An example could be a package of digital image processing methods that are sold to companies making end-user graphics programs.
The image processing company writes its classes to implement an interface, which it makes public to its customers. The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. While the image processing company's API is made public (to its customers), its implementation of the API is kept as a closely guarded secret—in fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.
Check out to learn more about interfaces.
In addition to what others have mentioned and by illogical comparison
it's a frame work for wrapping methods so they can be stored in
variables.
Thus on the fly you can equate the interface variable to be equal to any method or collection of methods atleast in this sense, a good reason you would usually want to do that is to escape repetitive logic that will definitely be an enemy of progress within the half life of your code at any decaying rate, be careful with the scenario below user discretion is advised.
SCENARIO
You have a game with a drawSillyThings() method in a SoulAvenger class, that has to draw some frames or sprites. Now drawSillyThings() has a list of other methods it needs to call in other to draw a metamorphed glorified-soul-ranger after user kills the grim-reaper in level 5k, i.e. drawSillyThings() needs to call either of inviteTheGrimReaper(), drawUpperCut(), drawTotalKO(), drawVictoryAndGlorifiedRanger(), drawDefeatAndMockery(), drawFightRecap() and drawGameOver() whenever the right situations arise during the gaming experience but all these would result in unwanted logic in drawSillyThings() which might slow the game i.e.
public static class SoulAvenger{
public SoulAvenger(){
//constructor logic
}
private void loadLevel5k(){...}
private void dontAllowUserWinOnTime(){...}
private void loadGrimReaperFight(){...}
private void drawSillyThings(){
... //unaccounted game logic
while(fighting_in_level_5k){
while(soul_ranger_has_enough_lives){
if(game_state=fight)inviteTheGrimReaper();
else if(game_state=medium_blows)drawUpperCut();
else if(game_state=heavy_blows)drawTotalKO();
else if(game_state=lost)drawDefeatAndMockery();
else if(game_state=won)drawVictoryAndGlorifiedRanger();
else if(game_state=end)drawFightRecap();
}else drawGameOver();
}
}
}
The problem here is the loop-nested boolean checks that have to be performed each time while the soul-ranger is still alive where as you could just have an alternative class which makes sure drawSillyThings() doesn’t need a game_state to be checked each time in order to call the right method but to do that you ‘ld need to kinda store the right method in a variable so that subsequently you can kinda variable = new method and also kinda variable.invoke(). If that wasn’t something have a look
public static class InterfaceTest{
public interface Method{
public void invoke();
}
public static void main(String[] args){
//lets create and store a method in a variable shall we
Method method_variable=new Method(){
#Override
public void invoke(){
//do something
}
};
//lets call or invoke the method from the variable in order to do something
method_variable.invoke();
//lets change the method to do something else
method_variable=new Method(){
#Override
public void invoke(){
//do something else
}
};
//lets do something else
method_variable.invoke();
}
}
This was probably what the guys at oracle had discovered was missing from Java several years before rumors of some developers planning a massive protest surfaced on the web but back to the SoulAvenger, as the gameplay occurs you would definitely just want to kinda have a variable be equated to give the right method to be invoked in drawSillyThings() in order to run things in a silly manner therefore
public static class SoulAvenger{
private interface SillyRunner{
public void run_things();
}
...//soul avenging variables
private SillyRunner silly_runner;
public SoulAvenger(int game_state){
//logic check is performed once instead of multiple times in a nested loop
if(game_state=medium_blows){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawUpperCut();
}
};
}else if(game_state=heavy_blows){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawTotalKO();
}
};
}else if(game_state=lost){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawDefeatAndMockery();
}
};
}else if(game_state=won){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawVictoryAndGlorifiedRanger();
}
};
}else if(game_state=fight){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawFightRecap();
}
};
}
}
private void loadLevel5k(){
//an event triggered method to change how you run things to load level 5k
silly_runner=new SillyRunner(){
#Override
public void run_things(){
//level 5k logic
}
};
}
private void dontAllowUserWinOnTime(){
//an event triggered method to help user get annoyed and addicted to the game
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawDefeatAndMockery();
}
};
}
private void loadGrimReaperFight(){
//an event triggered method to send an invitation to the nearest grim-reaper
silly_runner=new SillyRunner(){
#Override
public void run_things(){
inviteTheGrimReaper();
}
};
}
private void drawSillyThings(){
...//unaccounted game logic
while(fighting_in_level_5k){
while(soul_ranger_has_enough_lives){
silly_runner.run_things();
}
}
}
}
Now the drawSillyThings() doesn’t need to perform any if logic while drawing because as the right events gets triggered the silly_runner gets equated to have its run_things() method invoke a different method thus using a variable to store and invoke a method kinda-ish although in the real gaming world(I actually mean in a console) several threads will work asynchronously to change interface variables to run different piece of code with the same call.
An interface in java is a special type of Abstract class, the Interface provided the 100% Abstraction but since the java introduce new features in java 8 the meaning of whole Interface is change. Interfaces are used to tell what should be done. But due to new features now we give implementations of methods in Interface, that changed the meaning of Interface.
In Interface the method is public abstract by default
interface Bird{
void sound();
void eat();
}
Java doesn't provide the multiple inheritances feature mean a class doesn't have two parents, but we extend multiple Interfaces in java.
An interface is a contract between the system and the external environment. More specifically to Java - a contract for a class (for a specific behavior), implemented in a form that resembles a pure abstract class.
Which access modifier, in an abstract class, do I have to use for a method,
so the subclasses can decide whether it should be public or not? Is it possible to "override" a modifier in Java or not?
public abstract class A {
??? void method();
}
public class B extends A {
#Override
public void method(){
// TODO
}
}
public class C extends B {
#Override
private void method(){
// TODO
}
}
I know that there will be a problem with static binding, if
someone calls:
// Will work
A foo = new B()
foo.method();
// Compiler ?
A foo = new C();
foo.method();
But maybe there is another way. How I can achieve that?
It is possible to relax the restriction, but not to make it more restrictive:
public abstract class A {
protected void method();
}
public class B extends A {
#Override
public void method(){ // OK
}
}
public class C extends A {
#Override
private void method(){ // not allowed
}
}
Making the original method private won't work either, since such method isn't visible in subclasses and therefore cannot be overriden.
I would recommend using interfaces to selectively expose or hide the method:
public interface WithMethod {
// other methods
void method();
}
public interface WithoutMethod {
// other methods
// no 'method()'
}
public abstract class A {
protected void method();
}
public class B extends A implements WithMethod {
#Override
public void method(){
//TODO
}
}
public class C extends B implements WithoutMethod {
// no 'method()'
}
... then only work with the instances through the interfaces.
When overriding methods, you can only change the modifier to a wider one, not vice versa. For example this code would be valid:
public abstract class A {
protected void method();
}
public class B extends A {
#Override
public void method() { }
}
However, if you try to narrow down the visibility, you'd get a compile-time error:
public abstract class A {
protected void method();
}
public class B extends A {
#Override
private void method() {}
}
For your case, I'd suggest to make C not implementing A, as A's abstraction implies that there's a non-private method():
public class C {
private void method(){
//TODO
}
}
Another option is to make the method() implementation in C throwing a RuntimeException:
public class C extends A {
#Override
public void method(){
throw new UnsupportedOperationException("C doesn't support callbacks to method()");
}
}
What you are asking for is not possible for very good reasons.
The Liskov substitution principle basically says: a class S is a subclass of another class T only then, when you can replace any occurrence of some "T object" with some "S object" - without noticing.
If you would allow that S is reducing a public method to private, then you can't do that any more. Because all of a sudden, that method that could be called while using some T ... isn't available any more to be called on S.
Long story short: inheritance is not something that simply falls out of the sky. It is a property of classes that you as the programmer are responsible for. In other words: inheritance means more than just writing down "class S extends T" in your source code!
This is impossible because of the polymorphism. Consider the following. You have the method in class A with some access modifier which is not private. Why not private? Because if it was private, then no other class could even know of its existence. So it has to be something else, and that something else must be accessible from somewhere.
Now let's suppose that you pass an instance of class C to somewhere. But you upcast it to A beforehand, and so you end up having this code somewhere:
void somewhereMethod(A instance) {
instance.method(); // Ouch! Calling a private method on class C.
}
One nice example how this got broken is QSaveFile in Qt. Unlike Java, C++ actually allows to lower access privileges. So they did just that, forbidding the close() method. What they ended up with is a QIODevice subclass that is not really a QIODevice any more. If you pass a pointer to QSaveFile to some method accepting QIODevice*, they can still call close() because it's public in QIODevice. They “fixed” this by making QSaveFile::close() (which is private) call abort(), so if you do something like that, your program immediately crashes. Not a very nice “solution”, but there is no better one. And it's just an example of bad OO design. That's why Java doesn't allow it.
Edit
Not that I missed that your class is abstract, but I also missed the fact that B extends C, not A. This way what you want to do is completely impossible. If the method is public in B, it will be public in all subclasses too. The only thing you can do is document that it shouldn't be called and maybe override it to throw UnsupportedOperationException. But that would lead to the same problems as with QSaveFile. Remember that users of your class may not even know that it's an instance of C so they won't even have a chance to read its documentation.
Overall it's just a very bad idea OO-wise. Perhaps you should ask another question about the exact problem you're trying to solve with this hierarchy, and maybe you'll get some decent advises on how to do it properly.
Here is a part of the #Override contract.
The answer is : there isn't any possibility to achieve what you have.
The access level cannot be more restrictive than the overridden
method's access level. For example: if the superclass method is
declared public then the overridding method in the sub class cannot be
either private or protected.
This is not a problem concerning abstract classes only but all classes and methods.
THEORY:
You have the determined modifiers order:
public <- protected <- default-access X<- private
When you override the method, you can increase, but not decrease the modifier level. For example,
public -> []
protected -> [public]
default-access -> [public, default-access]
private -> []
PRACTICE:
In your case, you cannot turn ??? into some modifier, because private is the lowest modifier and private class members are not inherited.
I have multiple programs that I need to write which share common functionality/resources. I am looking to see if I can put a substantial part of these programs into a library. The scenario is as below:
ProgA, ProgB and ProgC are the programs using libX.
libX has a class XYZ which will instantiate a class ABC.
ProgA, ProgB and ProgC all have different implementations of class ABC.
How do I structure my program to make this happen? I have tried to do research, but was unable to find an answer. Thanks in advance...
You'll simply have a basic library interface ABC which provides the interface which allows your XYZ class to interact with the classes A, B and C which all implement interface ABC.
public interface ABC {
public void method1();
public void method2();
}
Your library class then just needs a reference to an object which implements interface ABC.
public class XYZ {
private ABC abc;
public XYZ(ABC abc) { this.abc = abc; }
}
And then your A, B and C implementations either implement ABC or create objects which implement ABC on-the-fly.
To me, it sounds a lot like a callback scheme. Yor library needs a standard way to communicate results to the specific implementation. ABC is basically an event handler interface.
it seems to mee like you need to create n inversion of control. In this case, you need libX to have a pointer to an interface ABC that has all the functionality you want to have libX use, and then, progA, progB and progC will have to implement this interface.
as you start your program, you need to go to the shared library and inject the running program into the library with a known method such as:
setProgram(IMyInterface interface) {
this.interface = interface;
}
this way, when you want to run your known response actions you run the this.interface.doSomething()and that 's it.
You may declare a public interface ABCInterface in your library which contains all methods neccessary for the operation of your library. Your different programs will then declare their classes ABC implementing this interface and pass the reference to your library's methods.
In case you need to instanciate the class (once or more often) inside your library you can pass reference to a factory instead of the class instance itself. The following code may give you an idea how to implement such functionality.
// Library code
interface ABCInterface {
public int getValue();
}
interface ABCFactory {
public ABCInterface createInstance();
}
class Library {
public static void doWork(ABCFactory factory) {
ABCInterface obj = factory.createInstance();
System.out.println(obj.getValue());
}
}
// Program code
class Program {
class ABCImplementation implements ABCInterface {
#Override
public int getValue() {
return 42;
}
}
public void useLibrary() {
Library.doWork(new ABCFactory() {
#Override
public ABCInterface createInstance() {
return new ABCImplementation();
}
});
}
}
What would be the practical side of the ability to define a class within an interface in Java:
interface IFoo
{
class Bar
{
void foobar ()
{
System.out.println("foobaring...");
}
}
}
I can think of another usage than those linked by Eric P: defining a default/no-op implementation of the interface.
./alex
interface IEmployee
{
void workHard ();
void procrastinate ();
class DefaultEmployee implements IEmployee
{
void workHard () { procrastinate(); };
void procrastinate () {};
}
}
Yet another sample — implementation of Null Object Pattern:
interface IFoo
{
void doFoo();
IFoo NULL_FOO = new NullFoo();
final class NullFoo implements IFoo
{
public void doFoo () {};
private NullFoo () {};
}
}
...
IFoo foo = IFoo.NULL_FOO;
...
bar.addFooListener (foo);
...
I think this page explains one example pretty well. You would use it to tightly bind a certain type to an interface.
Shamelessly ripped off from the above link:
interface employee{
class Role{
public String rolename;
public int roleId;
}
Role getRole();
// other methods
}
In the above interface you are binding the Role type strongly to the employee interface(employee.Role).
One use (for better or worse) would be as a workaround for the fact that Java doesn't support static methods in interfaces.
interface Foo {
int[] getData();
class _ {
static int sum(Foo foo) {
int sum = 0;
for(int i: foo.getData()) {
sum += i;
}
return sum;
}
}
}
Then you'd call it with:
int sum = Foo._.sum(myFoo);
I can say without hesitation that I've never done that. I can't think of a reason why you would either. Classes nested within classes? Sure, lots of reasons to do that. In those cases I tend to consider those inner classes to be an implementation detail. Obviously an interface has no implementation details.
One place this idiom is used heavily is in XMLBeans. The purpose of that project is to take an XML Schema and generate a set of Java classes that you can use bidirectionally to work with XML documents corresponding to the schema. So, it lets you parse XML into xml beans or create the xml beans and output to xml.
In general, most of the xml schema types are mapped to a Java interface. That interface has within it a Factory that is used to generate instances of that interface in the default implementation:
public interface Foo extends XmlObject {
public boolean getBar();
public boolean isSetBar();
public void setBar(boolean bar);
public static final SchemaType type = ...
public static final class Factory {
public static Foo newInstance() {
return (Foo)XmlBeans.getContextTypeLoader().newInstance(Foo.type, null);
}
// other factory and parsing methods
}
}
When I first encountered this it seemed wrong to bind all this implementation gunk into the interface definition. However, I actually grew to like it as it let everything get defined in terms of interfaces but have a uniform way to get instances of the interface (as opposed to having another external factory / builder class).
I picked it up for classes where this made sense (particularly those where I had a great deal of control over the interface/impls) and found it to be fairly clean.
I guess you could define a class that is used as the return type or parameter type for methods within the interface. Doesn't seem particularly useful. You might as well just define the class separately. The only possible advantage is that it declares the class as "belonging" to the interface in some sense.
Google Web Toolkit uses such classes to bind 'normal' interface to asynchronous call interface:
public interface LoginService extends RemoteService {
/**
* Utility/Convenience class.
* Use LoginService.App.getInstance() to access static instance of LoginServiceAsync
*/
class App {
public static synchronized LoginServiceAsync getInstance() {
...
}
}
}
With a static class inside an interface you have the possibility to shorten a common programming fragment: Checking if an object is an instance of an interface, and if so calling a method of this interface. Look at this example:
public interface Printable {
void print();
public static class Caller {
public static void print(Object mightBePrintable) {
if (mightBePrintable instanceof Printable) {
((Printable) mightBePrintable).print();
}
}
}
}
Now instead of doing this:
void genericPrintMethod(Object obj) {
if (obj instanceof Printable) {
((Printable) obj).print();
}
}
You can write:
void genericPrintMethod(Object obj) {
Printable.Caller.print(obj);
}
Doing this seems to have "Bad design decision" written all over it.
I would urge caution whenever it seems like a good idea to create a non-private nested class. You are almost certainly better off going straight for an outer class. But if you are going to create a public nested class, it doesn't seem any more strange to put it in an interface than a class. The abstractness of the outer class is not necessarily related to the abstractness of a nested class.
This approach can be used to define many classes in the same file. This has worked well for me in the past where I have many simple implementations of an interface. However, if I were to do this again, I would use an enum which implements an interface which would have been a more elegant solution.
The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?
public interface ITest {
public static String test();
}
The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".
There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between
public interface Foo {
public static int bar();
}
and
public interface Foo {
public static int bar() {
...
}
}
The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition.
Java could allow the latter; and in fact, starting in Java 8, it does!
The reason why you can't have a static method in an interface lies in the way Java resolves static references. Java will not bother looking for an instance of a class when attempting to execute a static method. This is because static methods are not instance dependent and hence can be executed straight from the class file. Given that all methods in an interface are abstract, the VM would have to look for a particular implementation of the interface in order to find the code behind the static method so that it could be executed. This then contradicts how static method resolution works and would introduce an inconsistency into the language.
I'll answer your question with an example. Suppose we had a Math class with a static method add. You would call this method like so:
Math.add(2, 3);
If Math were an interface instead of a class, it could not have any defined functions. As such, saying something like Math.add(2, 3) makes no sense.
The reason lies in the design-principle, that java does not allow multiple inheritance. The problem with multiple inheritance can be illustrated by the following example:
public class A {
public method x() {...}
}
public class B {
public method x() {...}
}
public class C extends A, B { ... }
Now what happens if you call C.x()? Will be A.x() or B.x() executed? Every language with multiple inheritance has to solve this problem.
Interfaces allow in Java some sort of restricted multiple inheritance. To avoid the problem above, they are not allowed to have methods. If we look at the same problem with interfaces and static methods:
public interface A {
public static method x() {...}
}
public interface B {
public static method x() {...}
}
public class C implements A, B { ... }
Same problem here, what happen if you call C.x()?
Static methods are not instance methods. There's no instance context, therefore to implement it from the interface makes little sense.
Now Java8 allows us to define even Static Methods in Interface.
interface X {
static void foo() {
System.out.println("foo");
}
}
class Y implements X {
//...
}
public class Z {
public static void main(String[] args) {
X.foo();
// Y.foo(); // won't compile because foo() is a Static Method of X and not Y
}
}
Note: Methods in Interface are still public abstract by default if we don't explicitly use the keywords default/static to make them Default methods and Static methods resp.
There's a very nice and concise answer to your question here. (It struck me as such a nicely straightforward way of explaining it that I want to link it from here.)
It seems the static method in the interface might be supported in Java 8, well, my solution is just define them in the inner class.
interface Foo {
// ...
class fn {
public static void func1(...) {
// ...
}
}
}
The same technique can also be used in annotations:
public #interface Foo {
String value();
class fn {
public static String getValue(Object obj) {
Foo foo = obj.getClass().getAnnotation(Foo.class);
return foo == null ? null : foo.value();
}
}
}
The inner class should always be accessed in the form of Interface.fn... instead of Class.fn..., then, you can get rid of ambiguous problem.
An interface is used for polymorphism, which applies to Objects, not types. Therefore (as already noted) it makes no sense to have an static interface member.
Java 8 Had changed the world you can have static methods in interface but it forces you to provide implementation for that.
public interface StaticMethodInterface {
public static int testStaticMethod() {
return 0;
}
/**
* Illegal combination of modifiers for the interface method
* testStaticMethod; only one of abstract, default, or static permitted
*
* #param i
* #return
*/
// public static abstract int testStaticMethod(float i);
default int testNonStaticMethod() {
return 1;
}
/**
* Without implementation.
*
* #param i
* #return
*/
int testNonStaticMethod(float i);
}
Illegal combination of modifiers : static and abstract
If a member of a class is declared as static, it can be used with its class name which is confined to that class, without creating an object.
If a member of a class is declared as abstract, you need to declare the class as abstract and you need to provide the implementation of the abstract member in its inherited class (Sub-Class).
You need to provide an implementation to the abstract member of a class in sub-class where you are going to change the behaviour of static method, also declared as abstract which is a confined to the base class, which is not correct
Since static methods can not be inherited . So no use placing it in the interface. Interface is basically a contract which all its subscribers have to follow . Placing a static method in interface will force the subscribers to implement it . which now becomes contradictory to the fact that static methods can not be inherited .
With Java 8, interfaces can now have static methods.
For example, Comparator has a static naturalOrder() method.
The requirement that interfaces cannot have implementations has also been relaxed. Interfaces can now declare "default" method implementations, which are like normal implementations with one exception: if you inherit both a default implementation from an interface and a normal implementation from a superclass, the superclass's implementation will always take priority.
Perhaps a code example would help, I'm going to use C#, but you should be able to follow along.
Lets pretend we have an interface called IPayable
public interface IPayable
{
public Pay(double amount);
}
Now, we have two concrete classes that implement this interface:
public class BusinessAccount : IPayable
{
public void Pay(double amount)
{
//Logic
}
}
public class CustomerAccount : IPayable
{
public void Pay(double amount)
{
//Logic
}
}
Now, lets pretend we have a collection of various accounts, to do this we will use a generic list of the type IPayable
List<IPayable> accountsToPay = new List<IPayable>();
accountsToPay.add(new CustomerAccount());
accountsToPay.add(new BusinessAccount());
Now, we want to pay $50.00 to all those accounts:
foreach (IPayable account in accountsToPay)
{
account.Pay(50.00);
}
So now you see how interfaces are incredibly useful.
They are used on instantiated objects only. Not on static classes.
If you had made pay static, when looping through the IPayable's in accountsToPay there would be no way to figure out if it should call pay on BusinessAcount or CustomerAccount.