Java interfaces reduction in visibility, only NOT [duplicate] - java

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;
}
}

Related

static interface factory methods [Java 8] [duplicate]

This question already has answers here:
Java - Alternatives to forcing subclass to have a static method
(5 answers)
Is there a way to make sure classes implementing an Interface implement static methods?
(9 answers)
Closed 5 years ago.
I want each class that implements an interface to have a static factory method, as defined by the interface. I.e:
public interface Handle {
public static Handle GetHandle() {
return null;
}
public void DoThings();
}
public class HandleA implements Handle {
private HandleA();
public static HandleA GetHandle() {
return new HandleA();
}
public void DoThings() {
return;
}
}
// This is allowed even though HandleB doesn't provide a GetHandle()
public class HandleB implements Handle {
private HandleB();
public void DoThings() {
return;
}
}
Reading past questions, it seems like the static method GetHandle() isn't enforced in concrete classes of Handle because that's not what the intended design behavior of static interface method is. Is there another way to do what I want? (i.e enforce all implementations of Handle to provide a "factory" GetHandle() method).
You cant enforce a class to have a static method in Java.

How to implement contradictory interfaces [duplicate]

This question already has answers here:
Java - Method name collision in interface implementation
(7 answers)
Closed 8 years ago.
Shortly I came across an oddity, I can't explain to myself. The real-world problem is already worked around, I'm just curious if there is an satisfying answer I didn't find.
Imagine you have to write a class that implements the following interface from some framework you are using:
interface Interface1 {
String method();
}
So far so good. Now you introduce a second framework and it would be rather useful if your class would implement a second interface:
interface Interface2 {
Long method();
}
That's the point where the problem arises:
class ThatsTheProblem implements Interface1, Interface2 {
public ???? method() {
// ...
}
}
Any ideas?
Just for your information: The real-world problem is based on an abstract-dao-pattern where some entities had Long ids, others had UUID ids.
Short answer: you can't.
What you can do is provide a view that implements one or the other interface. For instance:
public class OnePossibleSolution { // no "implements"
private String interface1Method() {
return "whatever";
}
public Interface1 asInterface1() {
return new Interface1() {
#Override
String method() {
return interface1Method();
}
}
}
// ditto for Interface2...
This is probably the most Java-idiomatic way to solve the problem. It's what Map does when you want to iterate over its elements, for instance. Rather than try to solve the problem of being an Iterable<K>, Iterable<V> and Iterable<Map.Entry<K,V>>, it provides three views:
keySet()
values()
entrySet()
Each of those returns a respective collection, which implements the appropriate Iterable<...> interface.
Two of the components of a method declaration comprise the method signature—the method's name and the parameter types. These methods have the same signature, therefore cannot be implemented by one class.
Remember that in Java, you don't neccesary have to store the result of a method. If your ThatsTheProblem class compiled, and you had a class with this code, to which version of the method would invoke?
ThatsTheProblem ttp = new ThatsTheProblem();
ttp.method();
It is clearly impossible to create one object that implements two conflicting interfaces. However, it is possible for one object to provide two different facades, each implementing conflicting interfaces.
Note here that the two facades refer to common instance variables of the one object so they do, essentially, represent the same object.
public interface Interface1 {
String method();
}
public interface Interface2 {
Long method();
}
public class DiMorph {
String forInterface1 = "Number nine";
Long forInterface2 = 9L;
public Interface1 asInterface1() {
return new AsInterface1();
}
private class AsInterface1 implements Interface1 {
#Override
public String method() {
return forInterface1;
}
}
public Interface2 asInterface2() {
return new AsInterface2();
}
private class AsInterface2 implements Interface2 {
#Override
public Long method() {
return forInterface2;
}
}
}
public void testInterface1(Interface1 i1) {
}
public void testInterface2(Interface2 i2) {
}
public void test() {
DiMorph m = new DiMorph();
testInterface1 (m.asInterface1());
testInterface2 (m.asInterface2());
}
To quote #Andreas, this is simply impossible.
Imagine you have two workers, Alice and Bob, with two managers, Cathy and Dave. Cathy expects Alice to implement the Work() method and return a Java application. Dave, on the other hand, expects Bob to implement the Work() method and return a C++ library. What your question suggests is to introduce a new worker Eric who can do the Work() of Alice and Bob at the same time. What actually happens is that Eric is too overloaded to compile.

How can we create object of interface in java? [duplicate]

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.

Java Abstract Methods [duplicate]

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.

Instantiating an Interface [closed]

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

Categories

Resources