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
I am starting java programming and I came across abstract classes. I know that you cannot instantiate them without creating concrete classes which extend them to become the subclass. However, I got really confused when I tried this code and it runs ok.
abstract class Communication{
public void FirstMethod()
{
System.out.println("I am first method()\n");
}
}
public class Main{
public static void main(String[] args){
Communication communication = new Communication() {
#Override
public void FirstMethod(){
super.FirstMethod();
}
};
communication.FisrtMethod();
}
}
Output is: I am first method().
If I modify it to:
Communication communication = new Communication() {
#Override
public void FirstMethod(){
System.out.println("I've been called from Main");
}
};
The output is: I've been called from Main.
Could somebody please explain if this is a kind of instantiation or what concept is this?
This is termed as
Anonymous Class
Definition:
An inner class declared without a class name is known as an anonymous inner class.
In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface.
This is called anonymous inner class. This way you can implement an interface or abstract class without having to find a name for it and instantiate it at the same time. This concept is useful when you use a certain implementation just once.
The construct looks always like that:
new SomeClass() {
//implementation of methods
};
This is known as anonymous class. The anonymous class definition allows you to provide a class definition within code and it has no formal name. The anonymous class expression has the class definition and instance creation expression.This is not limited to abstract classes but also for interfaces and concrete classes.
For example
abstract class A { }
// so the anonymous class expression is
A a = new A() {// class definition };
// This will actually create an instance of a
// class that extends the abstract class A
// that java will create at run time
You can even use anonymous class expression in the method arguments.Example of this is a Comparator in Collections.sort() method;
Collections.sort(listOfValues,new Comparator<Value>(){
public int compare(Value v1, Value v2){
// method implemetation.
}
})
This question already has answers here:
Calling super super class method
(12 answers)
Closed 8 years ago.
Let say I have three classes:
class A
{
public void method()
{ /* Code specific to A */ }
}
class B extends A
{
#Override
public void method()
{
/*Code specific to B*/
super.method();
}
}
class C extends B
{
#Override
public void method()
{ /* I want to use the code specific to A without using B */ }
}
The goal in this case is to use the code from A without using the code from B. I thought there was a way to do it by calling the super method, but this brings in the code from B as well.
Is there a way to do this?
The short answer is no. What you're seeing is that your design is flawed. It indicates that you need too move the code in class A out into a helper class. B and C would then use it via composition. You could try using partials to get the behavior you want. See this link for more details. Partial function application in Java 8
You could instantiate an object of class A in C and call the method method
class C extends B
{
#Override
public void method()
{ /* I want to use the code specific to A without using B */
A test = new A();
test.method();
}
}
Not sure if this is what you meant. Also asumed you forget the method name method in class A.
No there is no way to do it. You can simply create another method in class B that executes the code of A's method, and call that method in subclass C.
interface A
{
public void printValue();
}
public class Test
{
public static void main (String[] args)
{
A a1 = new A() {
public void printValue()
{
System.out.println("A");
}
};
a1.printValue();
}
}
We cannot create an instance of an interface, but what is new A() doing in this code? I have seen this type of code used mostly with Comparators. Please explain.
new A() {} is an instantiation of an anonymous class that implements interface A.
It is a short-cut that can be useful if you need an instance of a class that implements an interface only in one place, so you don't want to define a normal class. This way you define the class at the same place it is being used.
In your code sample, it doesn't seem very useful, but usually it is used by passing the anonymous class instance to some method that accepts a parameter of the type of the interface.
new A() in below is where you are instantiating a concrete class (which we say anonymous) which implements the interface A
A a1 = new A() {
public void printValue(){
System.out.println("A");
}
};
In your code, interface A is used as an Anonymous class. You can use them if you need to use a local class only once. it's more over same as lambda expressions.
Read more: http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Read about lambda expression: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
This question already has answers here:
This appears to create an object from an interface; how does it work?
(4 answers)
Closed 9 years ago.
How is this code working i m totally puzzled....
package com.servletpack.examples;
interface check {
public void message();
}
public class Interface {
public static void main(String[] args) {
try {
check t = new check() {//how????????????????
public void message() {
System.out.println("Method defined in the interface");
}
};
t.message();
} catch (Exception ex) {
System.out.println("" + ex.getMessage());
}
}
}
With that syntax, you create an anonymous class, which is perfectly legal.
Internally, anonymous classes are compiled to a class of their own, called EnclosingClass$n where the enclosing class' name precedes the $ sign. and n increases for each additional anonymous class. This means that the following class is being created:
class Interface$1 implements check {
public void message() {
System.out.println("Method defined in the interface");
}
}
Then, the code in main compiles to internally use the newly-defined anonymous class:
check t = new Interface$1();
t.message();
It is anonymous class. Your check class is an interface. Anonymous class defines an implementation of given interface on the fly. So it saves you from creating a seperate class for Interface's implementation. This approach is only useful when you know you will never require this implementation any where else in the code.
Hope this explanation helps !!
You are creating an instance (on the fly) of anonymous class that implements the interface check.
Your interface reference can hold the object of the implementing class. You are implementing an anonymous class and assigning it to the reference of interface, which is absolutely legal in JAVA.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interview : Can we instantiate abstract class?
I have an abstract class with all its methods defined (i.e. there are no abstract methods contained within it) like the following:
public abstract class MyAbstractClass {
String s;
public void setString(String s) {
this.s = s;
}
public String getString() {
return this.s;
}
}
There is also a JUnit test class:
public class TestClass {
MyAbstractClass c;
#Before
public void setUp() {
// What is happening here? And why does this work with an abstract class?
// Instantiation? Extending the abstract class? Overwriting?
c = new MyAbstractClass() { };
// This will not work: (Why?)
// c = new MyAbstractClass();
}
#Test
public void test_AllMethodsAvailable() {
// Why can I access the abstract class' methods?
// Shouldn't they be overwritten? Or did I extend the class?
c.setString("Test");
assertEquals("Test", c.getString());
}
}
I don't quite understand why the assignment to c works in the first case but not in the second, or what is actually happening there (and as a consequence, why accessing the abstract class' methods works in the test).
Can somebody please explain (and possibly point me to a Javadoc, article or book that explains why this works)?
Why can I "instantiate" an abstract class there? (Is that actually what I'm doing?)
Has it to do with inner classes?
You are creating an anonymous inner class with that code. The class you create this way is implicitly extending MyAbstractClass.
Since your abstract class does not have abstract methods you don't have to provide implementations so this works.
If you don't know about inner classes you can check the official documentation which is quite nice I think.
Has it to do with inner classes?
c = new MyAbstractClass() { };
Absolutely, the above is anonymous inner class declaration, you are not really instantiating an abstract class(which you can't) here but you are actually creating an Anonymous inner class(a sub-type of MyAbstractClass)
When you write c = new MyAbstractClass() { };, you actually create an anonymous class which extends MyAbstractClass, and which is not abstract. Since MyAbstractClass already has all method defined, the instanciation is valid.
Your assignment to c works because you are subclassing MyAbstractClass with an anonymous non-abstract class, the c is an instance of the non-abstract class.
Since you don't have any abstract methods in your abstract class, your anonymous class doesn't have to implement anything.