Can we create an instance of an interface in Java?
Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:
interface ProgrammerInterview {
public void read();
}
class Website {
ProgrammerInterview p = new ProgrammerInterview() {
public void read() {
System.out.println("interface ProgrammerInterview class implementer");
}
};
}
This works fine. Was taken from this page:
http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/
Creating instances of interface class java
You're seeing a case of Polymorphism, which is one of the core concepts that makes Interfaces useful.
InterfaceA x = (InterfaceA) factory.createFactoryObject(zz.CONST);
What's happening here is that factory.createFactorObject(zz.CONST); is returning an Object. I don't know precisely what kind of object it is, but if this code compiles and runs successfully, then the object must at least be of a class that implements InterfaceA. As a result, it has implementations for all the methods defined in InterfaceA.
So you can cast to InterfaceA, and take it as a given that you can use the methods defined in InterfaceA. The underlying JVM is responsible for knowing exactly how those methods were implemented (by the class the Object is instantiated from) and what to do if those methods are called.
Is it possible to create an object of an interface in java?
You never create an instance of just the interface. You can have a field/parameter/local variable of that interface type, but that's fine - the value that is assigned to such a variable will always be either null or a reference to an instance of some concrete implementation of the interface. The point is that code which deals only with the interface shouldn't need to care what the implementation is.
A good example is Collections.shuffle(List)
- I can provide that any list implementation, and it will only use the methods declared in the interface. The actual object will always be an instance of some concrete implementation, but the shuffle
method doesn't need to know or care.
Instantiate Interface without Implementation Class
Using anonymous inner class we can do it. Anonymous classes can implement interfaces, and i think at that time only you'll have a chance to see a class implementing an interface without the "implements" keyword.
interface Planet {
public void orbit();
}
class PlanetMain {
private Planet p = new Planet () {
public void orbit() {
System.out.println("interface Planet class executed");
}
};
}
How to create instance by interface using reflection?
I am not completely sure what you are trying to achieve. I'm assuming that UserService
is an interface?
If so it cannot be instantiated. You must either a class which implements the interface.
So either write a class (can also be anonymous or lambda) or use a proxy:
Object instance = Proxy.newProxyInstance(type.getClassLoader(),
new Class<?>[]{type}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//implement your methods here
//determine which method you're in by checking the method arg
}
});
Don't know if this is what you're after, but it is my best guess.
But maybe you're going at this wrong. When you're trying to replicate Spring, it is important that you have a component or bean you can autowire. So you should probably focus on your @Bean annotation (or similar) first. You'd want some sort of registry which picks up annotated beans and then injects them into your Autowired fields. It seems you have this back-to-front.
You should first focus on registering beans to your framework and only when you have achieved that you should try to inject them.
What is the purpose of creating an instance of Interface only?
1) No, they don't.
2) No.
What you are creating here is an anonymous class that implements your interface - notice that you were forced to implement the greet
method.
There are situations in your code when you simply do not care about giving your implementation a particular name - then you can pass the anonymous inner class - the whole concept of lambda expressions in Java is based on this.
Let's say you want to print the content of a list using the forEach
method:
Arrays.asList(1, 2, 3)
.forEach(...);
The forEach
accepts a Consumer
instance which is an interface. So, you could either create your own class:
class IntegerPrinter implements Consumer<Integer> {
@Override
public void accept(Integer integer) {
System.out.println(integer);
}
but that's too trivial to create a new class for it, so it is possible to pass an anonymous instance instead:
Arrays.asList(1, 2, 3)
.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println(integer);
}
});
A little bit better but still quite verbose. This is where lambda expressions come in handy:
Arrays.asList(1, 2, 3)
.forEach(integer -> System.out.println(integer));
How can we create an instance for Supplier as it is an Interface?
This snippet contains an anonymous class instance, which implements the Supplier<String>
interface.
It implements the only method of that interface with:
public String get() {
return "test";
}
which returns the String
"test".
Therefore, s.get()
returns the String
"test".
How to create a new object based on interface implementation
You can use reflection for this:
public void someMethod(MyInterface myInterface) {
Class<MyInterface> cl = myInterface.getClass();
MyInteface realImplementationObject = cl.newInstance(); // handle exceptions in try/catch block
}
Related Topics
Coding Conventions - Naming Enums
Is the Order Guaranteed for the Return of Keys and Values from a Linkedhashmap Object
Using Gzip Compression with Spring Boot/Mvc/Javaconfig with Restful
Hadoop No Filesystem for Scheme: File
How to Remove Single Character from a String
Is a Java Array of Primitives Stored in Stack or Heap
How to Convert Ascii Code (0-255) to Its Corresponding Character
Increasing the Jvm Maximum Heap Size for Memory Intensive Applications
Is There a Fixed Sized Queue Which Removes Excessive Elements
Open a Link in Browser with Java Button
How to Schedule a Task to Run at Periodic Intervals
Return Generated PDF Using Spring MVC
How to Generate the JPA Entity Metamodel
Run a Command Over Ssh with Jsch
Deserializing into a Hashmap of Custom Objects with Jackson