How do i ensure implementation of a public static function with interface - java

Since Java 8, we are able to define static and default methods in interface. But I need to ensure a public static method say foo() to be implemented in all the classes that implements a particular interface say interface A. How do I do that , or is it at all possible ?
The interface A:
package com.practice.misc.interfacetest;
public interface A {
public static Object foo(); //Eclipse shows error : 'This method requires a body instead of a semicolon'
String normalFunc();
}
Class B :
package com.practice.misc.interfacetest;
public class B implements A{
#Override
public String normalFunc() {
return "B.normalFunc";
}
//I need to ensure that I have to define function foo() too
}
Class C :
package com.practice.misc.interfacetest;
public class C implements A{
#Override
public String normalFunc() {
return "C.normalFunc";
}
//I need to ensure that I have to define function foo() too
}
Edit 1:
Actual case :
I have one public static method getInstance() (returning Singleton instance of that class) in all the implementing classes, and I want to ensure all the future classes other developers write must have that static method implemented in their classes. I can simply use reflection to return that instance by calling the getInstance() method from a static method of the interface, but I wanted to make sure that everyone implements the getInstance() in all the implementing classes.

static methods from interface are not inherited (1). They are inherited in case of a class, but you can not override them (2); thus what you are trying to do is literally impossible.
If you want all classes to implement your method, why not simply make it abstract (and implicitly public) to begin with, so that everyone is forced to implement it.

Eugene already pointed out that static methods can not be overridden. I suggest that you extract the singleton behavior to a separate interface. For example:
public interface A {
String normalFunc();
}
public class B implements A {
#Override
public String normalFunc() {
return "B.normalFunc";
}
// TODO add getInstance for singleton
}
public interface Singleton {
// TODO extensive javadoc to describe expected singleton behavior
A getInstance();
}
public class BSingleton implements Singleton {
#Override
public A getInstance() {
return B.getInstance();
}
}
Finally you can use any object of type BSingleton to get the singleton object of B.

Related

Can I call a static method on a generic class parameter

I have a collection of classes that implement RaeInterface:
public interface RaeInterface {
public static String SCHEMA_ID(){return ""; };
}
Each of the implementing classes have a different SCHEMA_ID() defined.
Id' like to pass a class to a method and use the static SCHEMA_ID() method on the class. I can pass the class to a method just fine, but getting at the static SCHEMA_ID() proves frustratingly hard.
public <T extends RaeInterface> void get( Class klass){
klass.SCHEMA_ID(); // <-- cannot resolve method.
}
Any suggestions on how to resolve this or is this even possible in Java 8?
Static methods cannot override in implementation of the Interface. If you want to override use default methods in interface.
Interface :
public interface RaeInterface {
default String SCHEMA_ID() {
return "";
}
}
Your mention method :
public <T extends RaeInterface> void get(T klass) {
klass.SCHEMA_ID();
}
Implement class :
class B implements RaeInterface {
#Override
public String SCHEMA_ID() {
return "B";//the ID
}
}
class C implements RaeInterface {
#Override
public String SCHEMA_ID() {
return "C";//the ID
}
}
I think you want an instance method in your interface:
public String schemaId();
Each implementing class can (and must if not abstract) implement this method. It doesn’t need to use any instance stuff for the implementation.
Your calling method gets much simpler and doesn’t need any generics:
public void get(RaeInterface instance){
instance.schemaId();
}
For inspiration you may look at how the java.util.Comparator interface is used. Usually classes implementing this interface don’t contain any instance variables, so you would think the compare method could just as well be static. Its probably only non-static to allow different implementations.
If you really insist on a static method, Sergey Lagutin is correct that reflection will solve your problem. But again, it’s getting more complicated and I don’t see why you should want such a solution.

static factory method in interface class java

I was reading Effective java text book. First item is about using static factory methods instead of public constructor. My doubt is that if i am specifying an Interface how can i specify a static factory method in the Interface ? Because java does not support static methods inside interface. The text book specifies about creating a non-instantiable class containing the public static factory methods. But how can those method access the private constructor of the implementation class?
The text book says if you are defining an Interface Type , create a non-instantiable class Types and include the static factory methods in that class. But how can a method defined in the Types class access the private constructor of a concrete implementation of Interface Type
EDIT:- Below sentence is quoted from the text book. Please explain me its meaning
"Interfaces can’t have static methods, so by convention, static factory methods for an interface named Type are put in a noninstantiable class (Item 4) named Types "
EDIT:- taken from Effective Java By Joshua Bloch: Item1 - Static Factory Method
public interface Foo{ //interface without plural 's' (question 1)
public void bar();
}
public abstract class Foos(){ // abstract factory with plural 's' (question 1)
public static Foo createFoo(){
return new MyFoo();
}
private class MyFoo implements Foo{ // a non visible implementation (question 2)
public void bar(){}
}
}
My question is that how can the static method createFoo() calls the private constructor of MyFoo
You can define the factory as returning the Interface but internally it creates a concrete class.
For example:
public Interface I { }
private class Impl implements I {
}
I buildI() {
return new Impl();
}
The trick is to create the implementations with package private (or even if they are inner classes private) constructors and then only the factory can build them.
The power of this method is that the factory can build the appropriate implementation depending on the requirements and that all happens invisibly to the user. For example when you create an EnumSet using the factory there are multiple internal implementations depending on how many entries there are in the Enum that the EnumSet is being built for. A super-fast version using bitfields on a long for Enums with less than 64 entries, a slower version for longer enumerations.
To specify the interface for a factory all you need to do is:
public interface Factory {
I buildI();
}
Now people can call you with setFactory(new FactoryImpl()); you can then call factory.buildI() and their code then returns the concrete implementation.
You can take this a step further and use Generics:
public interface GenericFactory<T> {
T buildInstance();
}
And then your setFactory becomes:
public void setFactory(GenericFactory<I> factory);
To create a factory they do:
public class FactoryImpl implements GenericFactory<I> {
#override
I buildInstance() {
return new impl();
}
}
But now you can use that same factory class for absolutely anything that needs a factory, just change the generics requirement.
The reason it can call the private constructor is very simple - it's declared in the same class!
Inside one Java file you can create the class with the private constructor. You then define the static method inside the class and even though it is static it still has the privileges required to access the constructor.
If the factory and implementation are in separate classes then they will be placed in the same package and the method made package private instead of private.
Java 8 finally allows interfaces to have static methods.
See this archived copy of the TechEmpower blog for details.
One way to think about this is with the package encapsulation in mind. Consider this Java 9+ code:
public interface Engine {
void start();
static Engine getEngine(String type) {
switch (type) {
case "combustion":
return new CombustionEngine();
case "electric":
return new ElectricEngine();
default:
throw new IllegalArgumentException("Unknown engine type : " + type);
}
}
}
class CombustionEngine implements Engine {
CombustionEngine() {
}
#Override
public void start() {
// injecting fuel and igniting it to create combustion...
}
}
class ElectricEngine implements Engine {
ElectricEngine() {
}
#Override
public void start() {
// electric current from battery flowing through coil in magnetic field...
}
}
Note that constructors in implementations are package-private so the caller from a different package can't instantiate implementation directly and should use the factory method.
Having the factory method in the interface
has no need for a dedicated EngineFactory class (the traditional implementation of Factory method design pattern)
reminds to Program to interface, not implementation
If needed, there is also a way to create implementation instances as singletons, which improves memory footprint :
public interface Engine {
enum EngineType {
COMBUSTION,
ELECTRIC;
private static EnumMap<EngineType, Engine> MAP = new EnumMap<>(EngineType.class);
static {
MAP.put(COMBUSTION, new CombustionEngine());
MAP.put(ELECTRIC, new ElectricEngine());
}
}
void start();
static Engine getEngine(EngineType type) {
return EngineType.MAP.get(type);
}
}
You cannot define a factory method in an interface, but you cannot have a constructor in an interface either: Interfaces cannot be instantiated. The point is to use a factory method instead of a constructor in the classes implementing the interface, not in the interface itself.
It talks about creating object via static factory method in the implementation not the interface
public Interface MyInterface {
public void myFunction();
}
public class MyClass implements MyInterface {
// constructor is made private
private MyClass() {}
// Use this to create object instead use static factory
public static MyClass getInstance() {
return new MyClass();
}
public void myFunction(){
// your implementation
}
}
A previous post also talks about static factory method.. What are static factory methods?
Apart from the book I also find the undermentioned link a good read
http://www.javacodegeeks.com/2013/01/static-factory-methods-vs-traditional-constructors.html

Return a private class implementing an interface keeping the implementation private

Static method M returns an object implementing interface A:
interface A { ... }
static A M() { ... }
Within M I would like to construct an object of type B and return that, given that B implements A:
class B implements A { ... }
I do not want client code to know anything about how B is implemented, I would prefer for B not to be a static class, B must be immutable and there could be different B handed to different clients. I want to prevent instantiation of B outside method M at all costs (short of reflection, as one user commented).
How can I achieve the above? Where and how should I implement B? Could you please provide a short code example?
My main problem is: how can I have "different Bs?"
A static inner class is probably your best bet. You won't be able to "prevent instantiation of B at all costs" since with reflection, client code can bypass all access modifiers.
You can use anonymous inner class that won't be called B (is anonymous) but will implement A for example
interface A {
void someMethod();
}
public class Test {
static A M() {
return new A() {// it will create and return object of anonymous
// class that implements A
#Override
public void someMethod() {
}
};
}
}
Without using reflection object of anonymous class can be created only by method M. Also it can't be extended so it is good first step to immutability.
You could also use a Proxy implementation to hide the implementation class further
public interface A {
public Object getValue();
}
public class Factory {
public static A newInstance() {
return new ProxyA(AImpl);
}
}
public class ProxyA implements A {
private A proxy;
public ProxyA(A proxy) {
this.proxy = proxy;
}
public Object getValue() {
return proxy.getValue();
}
}
All this is really doing is hiding the implementation of A under another layout and makes it difficult to create a instance of ProxyA
But as #Asaph points out, with reflection, it becomes next to near impossible to truly guard against people accessing various parts of the classes and objects...
You could also separate your interface and implementations via different Classloaders, so that you only ever expose the interface's to the developers and implementations are delivered by dynamic class loading them at runtime. While not solving the underlying problem, it further complicates the matters for those trying to circumvent your factory.
IMHO

How to refactor a class hierarchy of singletons where each class has a getInstance() method?

I have inherited a particular class hierarchy of singletons whose declarations are summarized below (there are more implementations -- I'm just showing the minimal set to demonstrate the problem). It smells to high heaven to me, foremost because singletons are being inherited from, as well as the way instance in the base class has its value overwritten in the static initializers of the subclasses.
If all the implementations were in the foo.common parent package I would consider just dropping the instance member and getInstance() methods from them, making the classes and their constructors package-local, and having some public factory class in foo.common create a single instance of each, hold onto that single instance of each internally (partitioned by whether it was an implementation of IReadOnly or IReadWrite) and provide a couple of public lookup methods where based on some enum it would return the asked-for implementation as the interface type.
But implementations can be outside of foo.common and foo.common isn't allowed to depend on such "more specific" packages, since foo.common is intended for stuff common to a bunch of apps. So something that simple can't be done. What then?
First interface:
package foo.common.config;
public interface IReadOnly
{
void load();
String getVal(String key);
}
Second interface:
package foo.common.config;
public interface IReadWrite extends IReadOnly
{
void save();
void setVal(String key, String value);
}
First implementation:
package foo.common.config;
public class ReadOnlyImpl implements IReadOnly
{
protected static IReadOnly instance;
static {
instance = new ReadOnlyImpl();
}
public static IReadOnly getInstance() {
return instance;
}
protected ReadOnlyImpl() {}
// implement methods in IReadOnly
}
Second implementation
package foo.common.config;
public class ReadWriteImpl extends ReadOnlyImpl implements IReadWrite
{
static {
instance = new ReadWriteImpl();
}
public static IReadWrite getInstance() {
return (IReadWrite) instance;
}
protected ReadWriteImpl() {
super();
}
// Implement methods in IReadWrite
}
Third implementation:
// While things in this package can depend
// on things in foo.common, nothing in
// foo.common is allowed to depend on this package.
package foo.apps.someapp;
public class MoreSpecificReadWriteImpl extends ReadWriteImpl
{
static {
instance = new MoreSpecificReadWriteImpl();
}
public static IReadWrite getInstance() {
return (IReadWrite) instance;
}
protected MoreSpecificReadWrite() {
super();
}
// Override superclass methods to do something specific
}
Putting package foo.apps.someapp aside, the design of the package foo.common.config is wrong.
IReadOnly o1=ReadOnlyImpl.getInstance(); // ok, returns ReadOnlyImpl
...
ReadWrite o2=ReadWriteImpl.getInstance(); // ok, returns ReadWriteImpl
...
IReadOnly o3=ReadOnlyImpl.getInstance(); // bad, returns ReadWriteImpl, the same as o2.
The reason is that all classes use the same static variable ReadOnlyImpl.instance. I would use separate variable in all classes, including MoreSpecificReadWriteImpl. If this would not fit, then think of using Spring container or similar framework.

Overriding a method

public class Testing extends JDialog {
public MyClass myClass;
public Testing() {
}
}
given the above code, is it possible to override a method in myClass in Testing class?
say myClass has a method named computeCode(), will it be possible for me to override it's implementations in Testing? sorry it's been a long time since I've coded.
if you want to override a method from MyClass then your testing class must extend that. for overriding a method one must complete IS-A relationship whereas your code comes under HAS-A relationship.
Yes, it is generally possible (note that as others have correctly mentioned - you'd need to extend it to override the method). Refer to this sample:
public class Animal {
public void testInstanceMethod() {
System.out.println("The instance method in Animal.");
}
}
public class Cat extends Animal {
public void testInstanceMethod() {
System.out.println("The instance method in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
myAnimal.testInstanceMethod();
}
}
Not only is it possible, but it is a key feature in polymorphism an code reusability.
Note, however, that MyClass.computeCode might be final - in this case, it cannot be overridden.
You override methods of classes that you extend. Therefore, in your example your Testing class could override the various existing methods of JDialog. If you wanted to override computeCode() from MyClass (assuming it's not final), you should make Testing extend MyClass.
public class Testing extends MyClass
{
#Override
public int computeCode()
{
return 1;
}
}
You can override a class's method only in a subclass (a class that extends the class whose method you want to override). However, given your skeletal code, you can (within Testing) have a nested class that extends MyClass and force an instance of that nested class into the myClass instance variable... so, the answer must be "yes".
Whether that's the best choice (as opposed to using interfaces, rather than subclassing concrete classes, and relying on Dependency Injection to get the implementations most suited for your testing), that's a different question (and my answer would be, unless you're testing legacy code that you can't seriously refactor until it's well test-covered... then, probably not;-).
See, if you want to override method from MyClass then you need to extend it.
As per your code, it seems you want to make a wrapper wround MyClass.
Wrapper means, calling implemented class method will call method of MyClass.
I am just clearing how wrapping works as below.
public class Testing extends JDialog {
public MyClass myClass;
public Testing() {
}
public void someMethod() {
//Add some more logic you want...
...
..
myClass.computeCode();
}
}
thanks.
The wording of the question is confused and lost.
Here are some key points:
You can't #Override something that you didn't inherit to begin with
You can't #Override something that is final
Here's a small example:
import java.util.*;
public class OverrideExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>(
Arrays.asList("a", "b", "c")
) {
#Override public String toString() {
return "I'm a list and here are my things : " + super.toString();
}
};
System.out.println(list);
// prints "I'm a list and here are my things : [a, b, c]"
}
}
Here, we have an anonymous class that #Override the toString() method inherited from java.util.ArrayList.
Note that here, it's not class OverrideExample that overrides the ArrayList.toString(); it's the anonymous class that (implicitly) extends ArrayList that does.
All the above answers are valid. But, if you want to extend JDialog but still if you want to override a method of another class it is possible through interfaces. Interfaces won't have method definitions but will have method declarations. More about interfaces, you can read at http://java.sun.com/docs/books/tutorial/java/concepts/interface.html
In your case, you can make use of interface like this
public interface MyInterface{
public void myMethod();
}
public class Testing extends javax.swing.JDialog implements MyIterface{
public void myMethod(){
// code for your method
}
}
Since Testing class has already inherited JDialog, there is no way let it inherit MyClass again unless to implement an interface. What you can do is to use some design pattern. However this is not overriding, since there is no inheritance. The Adapter is the one you need. Again you are losing the flexibility of polymorphism.
public class Testing extends JDialog {
MyClass myClass = new MyClass();
public Testing() {
}
public void methodA(){
myClass.methodA();
}
}
class MyClass {
public void methodA(){}
}

Categories

Resources