This question already has answers here:
Can we create an object of an interface?
(6 answers)
Closed 7 years ago.
Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
Is it correct here?
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A
{
}
public class B implements A
{
}
public static void main(String[] args)
{
A test = new B();
//A test = new A(); // wont compile
}
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.
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/
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Short answer...yes. You can use an anonymous class when you initialize a variable.
Take a look at this question: Anonymous vs named inner classes? - best practices?
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes it is correct. you can do it with an inner class.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc
Related
This question already has answers here:
Can we create an object of an interface?
(6 answers)
Closed 7 years ago.
Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
Is it correct here?
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A
{
}
public class B implements A
{
}
public static void main(String[] args)
{
A test = new B();
//A test = new A(); // wont compile
}
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.
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/
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Short answer...yes. You can use an anonymous class when you initialize a variable.
Take a look at this question: Anonymous vs named inner classes? - best practices?
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes it is correct. you can do it with an inner class.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc
This question already has answers here:
Multiple inheritance for an anonymous class
(6 answers)
Closed 4 years ago.
It is clearly stated that interfaces don't have constructors. But when using anonymous inner classes we create an interface object and do overriding it methods. If there is no constructors in interfaces how this is possible.
For an example,
interface A{
void print();
}
class B{
public static void main(String args[]){
A a=new A(){
void print(){
System.out.println("Message");
}
};
}
}
How that A a=new A() is possible if interface is not having constructors?
The code
interface A {
void print();
}
class B {
public static void main(String[] args) {
A a = new A() {
public void print() {
System.out.println("Message");
}
};
}
}
is a shorthand for
interface A {
void print();
}
class B {
public static void main(String[] args) {
class B$1 extends java.lang.Object implements A {
B$1() {
super();
}
public void print() {
System.out.println("Message");
}
}
A a = new B$1();
}
}
With just one exception: If class B$1 is declared explicitly, it is possible to extend from it using class C extends B$1. However, it is not possible to extend from an anonymous class B$1 (JLS §8.1.4), even though it is not final (JLS §8.1.1.2).
That is, anonymous classes are still classes. As all classes (except java.lang.Object itself), even these classes extend java.lang.Object, directly or indirectly. If an anonymous class is specified using an interface, it extends java.lang.Object and implements that interface. If an anonymous class is specified using a class, it extends that class. In case the constuctor has arguments, the arguments are forwarded to super().
You can even (although definitely not recommended at all) insert a A a2 = new B$1(); later in main(), if you like. But really, don't do that, I'm just mentioning it to show what's going on under the hood.
You can observe this yourself by putting your source code in a separate directory, say, into AB.java, compile it, and then
look at the class files that were generated.
Use javap -c B$1 to see how the anonymous class was generated by javac.
Every class has a default constructor which is the no-argument constructor if you don't define another constructor. And the anonymous class implement the interface will automatically generate it unless you define another constructor.
This question already has answers here:
Inner class within Interface
(13 answers)
Closed 7 years ago.
In which scenario can an interface have nested classes?
The following code is allowed and valid.
public interface Iface {
void show();
class ifaceClass {
int x;
public ifaceClass() {
System.out.println(x);
}
}
}
I am also struggling to make object of class ifaceClass.
EDIT :
I am able to make object like this
public class Test implements Iface {
public static void main(String[] args){
ifaceClass ifaceClassObj = new ifaceClass();
}
public void show() {
}
}
I noticed if Test has not implemented the Iface then I needed following import,
import com.jls.Iface.ifaceClass;
But it boiled down to same problem that why not use it as a just another class.
What the difference or value addition with this approach ?
You can create an instance of ifaceClass inside the class that implements Iface:
interface Iface {
void show();
class ifaceClass {
int x;
public ifaceClass() {
System.out.println(x);
}
}
}
public class Test implements Iface {
public static void main(String args[]) {
ifaceClass iface = new ifaceClass();
}
#Override
public void show() {
// ...
}
}
If the class doesn't implement the interface, just create an instance like this:
Iface.ifaceClass iface = new Iface.ifaceClass();
Why create a class inside an interface? Basically for the same reason you create a class inside another class, to group related classes together.
Where it is useful to have nested classes in an interface?
There is no such case which can only be fulfilled with inner class of interface. It is syntactically valid to have inner class in interface and for the class which implement interface can create instance of class and apart from that Interface.Class can also make that class accessible because it can not be private at all.
I noticed if Test has not implemented the Iface then I needed
following import import com.jls.Iface.ifaceClass;
Not necessarily, if your interface is accessible your inner class will automatically become accessible.Here you are trying to access class directly without even importing interface in that case following statement need above import statement.
ifaceClass ifaceClassObj = new ifaceClass();
But it boiled down to same problem that why not use it as a just
another class. What the difference or value addition with this
approach
Exactly, creating another class can also provide you the same facility and I have never seen any use case in my day to day programming which can only be fulfilled with inner class of interface.It does not provide anything else than accessibility through the interface.
I have used it once which I think quite a bad practice though. One day we need to implement one common method in different classes which are implementing interface say X and we wanted to add one extra method to be used by all this classes to add one kind of check on the Object which only check some parameter and return boolean even though that use case can be fulfilled in other way but to be specific that it is only intended for classes which are implementing this interface we have added class in interface so that we can provide that method to implementing classes.(NOTE : Nowadays default method can be used in this case instead of inner class)
Here, it is wise to note that in huge projects it is quite impossible for anyone ( other than creator ) to note that any interface has inner class. So, until we implement that class or manually check the interface we can not came to know that interface has inner class.
We all know that you can't instantiate an interface in Java (directly at least).
But with something like this:
public class Test{
public interface Link {
void mySamplemethod();
String myString ="HELLO!";
}
public static void main(String []args){
Link b;
}
}
What exactly is b... and how could it ever have a practical purpose?
b is a variable of type Link that has no value, not even null. In order to have a practical purpose you must initialize it with an object reference whose class implements Link interface.
If you want to initialize Link with a non-null value, you should create a class that implements this interface. That's mandatory in Java. If you don't want to create a new class outside this class, you can create a new class inside the class or inside the method (which would be an anonymous class). Here's a sample:
public static void main(String []args){
Link b = new Link() {
#Override
public void mySampleMethod() {
System.out.println("hello");
}
};
b.mySampleMethod();
}
The purposes of using interfaces for programming instead of direct classes is already explained very well here: What does it mean to "program to an interface"? (no need to reinvent the wheel).
You can create a reference to an interface - you just cannot instantiate it. Let's say for example you have a interface A
public interface A {
public void someMethod();
}
Now you have another class that implements this interface
public class B implements A {
public void someMethod() { // do something }
public void someOtherMethod() { // do something else }
}
Now you can have something like
A a = new B();
While a reference type A it actually implements the method as defined in B. The object type is B. The reference type A indicates that it has only access to those methods in B that are specified by A and nothing else (in this case, it has access to someMethod() and not someOtherMethod()).
What exactly is b...
b contains a reference to an instance of a class that implements Link. The reference can, of course, be null.
and how could it ever have a practical purpose?
Its practical purpose is pretty much the same as any other Java reference.
Of course, the code as it is does not really put b to any use. However, it's not hard to imagine similar code that would (you'd need to have a class that implements Link, and create an instance of that class).
For instance interfaces are widely used in polymorphism. So if you have multiple classes implementing interface, you could keep them in the same way:
class One implements Link {..}
class Two implements Link {..}
public static void main(String[] arg) {
Vector<Link> links;
Link link1 = new One();
Link link2 = new Two();
links.add(link1);
links.add(link2);
for (Link l : links) {
l.mySampleMethod();
}
}
Is it possible to compose new class at runtime in Java?
What are the means for that? Refection? Compiler API?
I can do
package tests;
public class TryReflection02 {
interface A {
}
public static void main(String[] args) {
Object o = new A() {};
System.out.println( o.toString() );
o = A.class.newInstance() // exception
}
}
Can I do the same having A.class value?
No, you can't. A is an interface, and only classes can be instantiated.
What you can do is to use a library/helper that uses some trickery to create a class that implements the interface and instantiates that. The JDK's Proxy class contains static methods to do just that. There are also tools that can do it which are custom-geared for test-related use cases: mockito, for instance.
These tools do exactly what you hint at in this question's title: rather than instantiating the interface, they generate a new class that implements the interface, and then instantiate that class.