As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Say i have an interface I with method doIt();
Now i have a class C that implements I and hence provides the implementation for doIt();
For the following code in Class Hello
public class Hello{
I i = new I();
i.doIt();
}
1.) Now where does it take the implementation of doIt() from?
2.) What if there was another class HelloWorld implementing I too with a different iplementation for the doIt() function. Then which implementation would it have taken?
Try compiling this stuff. You can only instantiate a Class which implements the Interface and not the Interface directly.
An Interface is just like a contract which a Class agrees to when it implements it; and within the agreement of the Interface, Class provides the implementation of it.
You cannot instantiate an interface. You can only instantiate a concrete class. The implementation of doIt() is the one defined in the concrete class that was instantiated. If that class doesn't provide an implementation, it gets inherited from a superclass.
As a sidenote, in your code example, you have code in a class that is not contained within a method or static block. This is not legal. You must enclose code in a method or static block.
Interfaces cannot be instantiated. The code you have posted should not compile. What you can do is something like so: I c = new C();. This will also make sure that the appropriate implementation of doIt() will me called.
Refer to this Oracle tutorial for more information on Interfaces.
This will never work
public class Hello{
I i = new I(); // I is an interface, can't be instantiated
i.doIt();
}
I think you want...
public class A implements I {
public void doIt() {
System.out.println("A did it");
}
}
public class B implements I {
public void doIt() {
System.out.println("B did it");
}
}
public class Main {
public static void main(String args[]) {
I i = new A();
i.doIt();
i = new B();
i.doIt();
}
}
This will output
A did it
B did it
Only way around to instantiate interface is to add anonymous inner type specific to your implementation. Though it looks like a bad design sometimes it's useful. cheers.
II i = new II() {
#Override
public void doit() {
// TODO Auto-generated method stub
}
};
There is no implemenatation and your code will not compile. Try creating a simple working example and you will understand. BTW the syntax is wrong anyway: if I is an interface, you need opening curly braces to create an anonymous class implementing the interface:
I i = new I() { public void doIt() {} };
In your code I i = new I(); is incorrect as I is an interface and interface cannot be instantiated , if you have to do it then this should be
I i = new I(){
public returntype doIt(){
...
}
};
now the above implementation is known as Anonymous Inner Classes here
Related
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:
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:
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reduce visibility when implementing interface in Java
I must be missing something obvious, but i am getting:
Cannot reduce the visibility of the inherited method
And I don't see how. This is my interface:
interface QueryBuilderPart {
StringBuilder toStringBuilder();
}
And this is my implementation:
public class Stupid implements QueryBuilderPart {
#Override
StringBuilder toStringBuilder() {
return null;
}
}
Both the class and the implementation are in the same package. Any Ideas?
By default interface's method is public, but you reduce it to default visibility, which is package level visibility.
So the following two block of code are the same:
interface QueryBuilderPart {
StringBuilder toStringBuilder();
}
interface QueryBuilderPart {
public abstract StringBuilder toStringBuilder();
}
Note that interface's method is abstract as well
So you should do as following:
public class Stupid implements QueryBuilderPart {
#Override
public StringBuilder toStringBuilder() {
return null;
}
}