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.
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:
What is the "default" implementation of method defined in an Interface?
(3 answers)
Closed 4 years ago.
A java interface say "TestInterface" having 2 methods method1(), method2() is implemented by 100 different classes. Now I need to introduce a new method in TestInterface without making changes to other classes which already implemented it. How do I achieve it in java?
In my experience, the best way to do this is often to extend your Interface
public interface TestInterfaceEx extends TestInterface
Then, you can add methods to TestInterfaceEx, have the classes you want implement that, and use
if (myinstance instanceof TestInterfaceEx) {
myinstanceEx = (TestInterfaceEx) myinstance;
//...
}
in places where you want to use this new functionality
now from java 8 you can add default method in your interface, that method(default method in the interface) is present in all the classes that will implement it....
Ex :--
public class Java8Tester {
public static void main(String args[]) {
Vehicle vehicle = new Car();
vehicle.print();
}
}
interface Vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
interface FourWheeler {
default void print() {
System.out.println("I am a four wheeler!");
}
}
class Car implements Vehicle, FourWheeler {
public void print() {
Vehicle.super.print();
FourWheeler.super.print();
Vehicle.blowHorn();
System.out.println("I am a car!");
}
}
From Java8:
For example, if several classes such as A, B, C and D implement an interface XYZInterface then if we add a new method to the XYZInterface, we have to change the code in all the classes(A, B, C and D) that implement this interface. In this example we have only four classes that implement the interface which we want to change but imagine if there are hundreds of classes implementing an interface then it would be almost impossible to change the code in all those classes. This is why in java 8, we have a new concept “default methods”. These methods can be added to any existing interface and we do not need to implement these methods in the implementation classes mandatorily, thus we can add these default methods to existing interfaces without breaking the code.
We can say that concept of default method is introduced in java 8 to add the new methods in the existing interfaces in such a way so that they are backward compatible. Backward compatibility is adding new features without breaking the old code.
The method newMethod() in MyInterface is a default method, which means we need not to implement this method in the implementation class Example. This way we can add the default methods to existing interfaces without bothering about the classes that implements these interfaces.
interface MyInterface{
/* This is a default method so we need not
* to implement this method in the implementation
* classes
*/
default void newMethod(){
System.out.println("Newly added default method");
}
/* Already existing public and abstract method
* We must need to implement this method in
* implementation classes.
*/
void existingMethod(String str);
}
public class Example implements MyInterface{
// implementing abstract method
public void existingMethod(String str){
System.out.println("String is: "+str);
}
public static void main(String[] args) {
Example obj = new Example();
//calling the default method of interface
obj.newMethod();
//calling the abstract method of interface
obj.existingMethod("Java 8 is easy to learn");
}
}
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:
Abstract methods in Java
(3 answers)
Closed 8 years ago.
I am slightly confused with the keyword abstract here. My compiler is telling me that I am not allowed to have a body for a method that's abstract. However my assignment says:
The abstract method orderDescription() returns a String giving details about a particular order.
abstract String orderDescription()
{
return null;
}
However my code returns an error, as I mentioned above. So my question is what should I do for this problem?
Up to now I've just removed the keyword abstract and it works fine.
abstract String orderDescription()
{
return null;
}
should be
abstract String orderDescription();
As error says, your abstract method declaration shouldn't contain any body.
Above syntax mandates the implementation (which ever class extends the abstract class and provides implementation) to return a String.
You can't instantiate abstract class, so some class need to extend abstract class and provide implementation for this abstract method.
Example:
class MyabsClass
{
abstract String orderDescription();
}
class MyImplementation extends MyabsClass
{
public String orderDescription()
{
return "This is description";
}
}
class MyClient
{
public static void main(String[] args)
{
MyImplementation imple = new MyImplementation();
imple.orderDescription();
}
}
When you define an abstract method, you are telling the compiler that any subclasses must provide an implementation (or also declare themselves abstract).
You implement the abstract method in a subclass.
Remember, you cannot create instances of abstract classes themselves. The entire point of an abstract method is to tell the compiler that you want subclasses to provide the functionality.
Essentially, an abstract function shouldn't contain any details, it is a placeholder function for inherited functions. As Nambari stated, you should only include the definition.
This is used for when you want a family of classes to all contain a common function, which you wish each child class to define.
Abstract methods generally shouldn't contain any "real" code, abstract methods are to be overidden by non-abstract classes containing the method.
Abstract method should not have any method body. It allows only method declaration.
Also, adding to Nambari's example, what you can do is
class MyabsClass
{
abstract String orderDescription();
}
class MyClient
{
public static void main(String[] args)
{
MyabsClass mac = new MyabsClass(){
public String orderDescription()
{
return "This is description";
}
};
mac.orderDescription();
}
}
That is, through anonymous class.
I was reading some sourcecode from Java libraries, and I am confused here;
This code is from Document.java in jaxb library, and ContentVisitor is an Interface in same package, how can we create an instance of Interface with a new keyword? isn't that illegal?
public final class Document {
.
.
private final ContentVisitor visitor = new ContentVisitor() {
public void onStartDocument() {
throw new IllegalStateException();
}
public void onEndDocument() {
out.endDocument();
}
public void onEndTag() {
out.endTag();
inscopeNamespace.popContext();
activeNamespaces = null;
}
}
In the code, you're not creating an instance of the interface. Rather, the code defines an anonymous class that implements the interface, and instantiates that class.
The code is roughly equivalent to:
public final class Document {
private final class AnonymousContentVisitor implements ContentVisitor {
public void onStartDocument() {
throw new IllegalStateException();
}
public void onEndDocument() {
out.endDocument();
}
public void onEndTag() {
out.endTag();
inscopeNamespace.popContext();
activeNamespaces = null;
}
}
private final ContentVisitor visitor = new AnonymousContentVisitor();
}
It's valid. It's called Anonymous class. See here
We've already seen examples of the syntax for defining and instantiating an anonymous class. We can express that syntax more formally as:
new class-name ( [ argument-list ] ) { class-body }
or:
new interface-name () { class-body }
It is called anonymous type/class which implements that interface. Take a look at tutorial - Local and Anonymous Inner Classes.
That declaration actually creates a new anonymous class which implements the ContentVisitor interface and then its instance for that given scope and is perfectly valid.
There's something called anonymous class in java http://www.java2s.com/Code/Java/Class/Anonymous-class.htm
Do notice where the braces open - you are declaring an inner object (called anonymous class) that implements ContentVisitor and all required methods on the spot!
It is inline interface implementation.Here the idea is to have the compiler generate an anonymous class that implements the interface. Then for each method defined in the interface you can (optionally) provide a method with a suitable signature that will be used as the implementation of the interface's method.
It is the new Oxygene syntax, added to the language to allow Oxygene programmers to work with these interface-based events in much the same way as Java programmers do.
You actually have just provided the implementation of this interface in an anonymous way. This is quite common and of course possible. Have a look here for more information.
Since the question is still actual and Java 8 brought in lambda. I must mention it. Lambda comparing with AIC has a couple of advantages.
readability / introduce functional programming.
in some cases performance.
But lambda and AIC have different scope. You can't create an instance of Lambda and obtain a reference to lambda itself.