I was trying to figure out how to do simple implementations and I thought, what if the interface extends to another interface?
so for example,
public interface A{
public void a();
}
public interface B{
public void b();
}
public interface C extends B, A {
public void c();
}
If I was to implement interface C on another class what do I have to do?
I tried this from reading other threads:
public class Example<E extends B&A> implements C{
public void c(){
}
}
Which doesn't seem to be right.
Whats wrong with ... simply implementing all interfaces?
public class Example implements C {
#Override
public void a(){ }
#Override
public void b(){ }
#Override
public void c(){ }
}
In other words: what do you think to gain from making Example a generic type in the first place?!
Meaning: if there is a deeper problem that I don't see - you should consider updating your question and explain what you intend to do (to avoid solving a xy problem here). If there is no deeper problem, go with the most simple solution (like the one shown above).
If you want your Example class to implement C... all you need to do is to say implements C. The type variable is quite separate and irrelevant to this:
public class Example implements C { ... }
But looking at your class signature:
public class Example<E extends B&A> implements C
E is a type variable which allows you to handle references to classes implementing both B and A (but not C).
For example, if there is a method in Example taking an E as a parameter:
void someMethod(E e)
then you can have the following in its body:
void someMethod(E e) {
e.a(); // OK.
e.b(); // OK.
// e.c(); // Compiler error, E doesn't implement C.
}
Related
This question was asked to me in an interview. Tired of googling here I am.
I have an interface with 100 methods. I don't want to implement all those 100 methods in a single class. Is there any way I could implement these 100 methods by using more than one class and not repeating the implementation ?
For Example :
Class A implements first 10 methods(only).
Class B implements next 10 methods(only) and so on.
Note :
1. All the classes which implements the interface must be concrete.
As far as my knowledge on java this isn't possible. He mentioned about adapter when he asked me this question. That made me think that there's a way to do it.
Can anybody clarify me on this ?
Write an adapter with empty implementation of the 100 methods
class Adapter{
//write your empty implementations here as similar to KeyListener in Java
// They have written a keyAdapter and make use of key adapter.
}
ie) class Adapter implements interface1{
public void method1(){}
public void method2(){}
.....
}
You can extend the adapter class in some other class and just override the methods.
class A extedns Adapter{
public void method1(){
}
}
ie)
The concept you describe is called partial classes and Java does not have such a concept.
Here is a similar answer: A way to implement partial classes in java
If you use Java 8 , you can define default implementations in the interface for the 100 methods like :
public interface MyInterface{
void methodA();
int methodB();
default boolean methodC(String name) {
return name.equals("Default");
}
}
Then in your concrete classes you only implements the methods you want. All other not overriden methods will use the default implementation from the interface.
You will have to write 100 default implementations in the interface but it will save you the need to also write 100 implementations in every concrete class implementing that interface.
Again, this is only available since Java 8.
Write all the classes (A, B, C, D, E each implement 20 methods) witch extend one another without implementing the interface I:
I
|
A <- B <- C <- D <- E
And only the last one implements the interface.
Simpler exemple with only 2 methods:
public interface I {
void a();
void b();
}
public class A {
public void a() {
}
}
public class B extends A implements I {
public void b() {
}
}
If the interface methods defined with default implementation ;
public interface I {
default void a(){
//implementation
}
default void b(){
//implementation
}
default void c(){
//implementation
}
//97 more
}
public class A implements I{
#override
public void a() {
}
}
public class B extends A {
#override
public void b() {
}
public class C extends B {
#override
public void c() {
}
}
Even without inheritance classes can be independent from each other and they can provide implementation for different methods
You are correct - any concrete class must implement all methods, so the only way you can not do it is either extend the class that implements given interface and override some of the methods in subclass or implement methods calling implementations from other classes
I have a classic diamond inheritance problem where
A
/ \
B C
\ /
D
are all interfaces, and I have
AImpl(A)
| \
| \
BImpl(B) CImpl(C)
| \
| \
DImpl(B,C) \
| F(C)
|
E(B,C)
where class E implements both interfaces B and C, but F implements only interface C.
Due to the lack of multiple inheritance, I currently have duplicated functionality in DImpl and CImpl.
I just fixed a bug in CImpl, but forgot to do the same for DImpl. Obviously remembering to always copy code from CImpl to DImpl and vice versa is not very sustainable as the code base keeps growing. Are there any established best practices for putting the shared code of both in a single place, despite the disallowance of multiple inheritance?
EDIT -- Solution with multiple inheritance would have been to have DImpl inherit CImpl.cFunction() instead of redefining DImpl.cFunction as a copy of CImpl.cFunction
EDIT 2 -- Sample code:
public interface Animal {
public void eat();
}
public interface FlyingAnimal extends Animal {
public void fly();
}
public interface RunningAnimal extends Animal {
public void run();
}
public interface Monster extends FlyingAnimal, RunningAnimal {
public void roar();
}
public class AnimalImpl implements Animal {
#Override
public void eat() {
...
}
}
public class FlyingAnimalImpl extends AnimalImpl implements FlyingAnimal {
#Override
public void fly() {
...
}
}
public class RunningAnimalImpl extends AnimalImpl implements RunningAnimal {
#Override
public void run() {
...
}
}
public class MonsterImpl extends FlyingAnimalImpl implements Monster {
#Override
public void run() {
...
}
#Override
public void roar() {
...
}
}
public class ScaryMonster extends MonsterImpl implements Monster {
public void sneakAround() {
...
}
}
public class Human extends RunningAnimalImpl implements RunningAnimal {
public void scream() {
...
}
}
Now if I find a bug in RunningAnimalImpl.run() and I fix it, I have to remember to copy the fix over to MonsterImpl.run().
This is a very poor design. You should not have a diamond structure in the first place just because it is possible in interfaces.
One of the basic principle of OOP is
Prefer composition over inheritance!
What I am saying is you don't need interface D at all. Wherever you need to use DImpl simply provide reference to interface A and then based on your runtime need pass BIml or CImpl instance to it. That way all you have to change is BImpl code or CImpl code for bug fix and it will be used anywhere you are using DImpl instance today.
As per your comment the code would be something like -
public class ScaryMonster {
Animal animal;
public ScaryMonster(Animal animal) {
this.animal = animal;
}
public void fly() {
if(animal instanceof FlyingAnimal ) {
((FlyingAnimal )animal).fly();
}
else {
throw new Exception("This mosnter cannot fly");
}
}
public void run() {
if(animal instanceof RunningAnimal ) {
((RunningAnimal )animal).run();
}
else {
throw new Exception("This mosnter cannot run");
}
}
public void sneakAround() {
...
}
}
If you want your monster to both fly and run pass instance of MonsterImpl to the constructor. Note now ScaryMonster does not extend or implement anything.
This is what I am saying - Prefer composition over Inheritance!.
In Java 8 you can implement default methods within interfaces so if you have an interface with common implementations just define them inside of the interface and override them whenever you need to change it up a bit. Of course this is assuming you are using Java 8.
For example:
public interface A {
default void cFunction(){
System.out.println("Calling A.cFunction");
}
}
public class DImpl implements A {
}
DImpl can call cFunction and it will default to calling the interfaces implementation.
In the case which 2 interfaces have a method with the same signature you can call them by referencing the interface name along with the method such as A.super.cFunction()
More meaningful example:
public interface Driveable {
default void start(Vehicle vehicle){
System.out.println("Starting my driveable thing");
vehicle.mileage++;
}
}
public interface Machine {
default void start(){
System.out.println("Starting my machine");
}
}
public class ElectricCar extends Vehicle implements Driveable, Machine {
public void start(){
Driveable.super.start(this);
}
}
public class DIYCar extends Vehicle implements Driveable, Machine {
public void start(){
System.out.println("instant fire");
}
}
As you can see you can implement a default method in your interface and use it within your concrete class. In this scenario an ElectriCar is Driveable and a Machine but we want it to use the Driveable start() method because at the end of the day no matter how many machines (computers) are in our car, we still just want to drive it.
This is just an example and although the example may be a bit strange I hope it helps get the point across of being able to implement default methods.
UPDATE for your example source:
In your case of your Monster and Animal being able to run, you should have a RunnableCreature interface with an implementation of run(). This way if a Monster and Animal run the same they can reference the default run() method, otherwise it can override it and implement its own.
If you need your default method to manipulate variables two (or more) of your classes that have the same run() method would have common attributes and therefore should have a common base class. You can pass this base class to the default method and manipulate its variables as needed.
Don't implement C in D, instead of inheritance compose it within D. In that way you dont duplicate your code and have just one implementation of C.
If you somehow needs to inherit from C (which i think you would need to review design then), then i would still suggest you compose C and implement all the methods of C within D and delegate calls via composed object.
A common alternative would be to use composition instead of inheritance. Does it make sense to say that D is a B and is also a C? Does D really need to expose every public method contained in B and C? If the answer to any of these questions is no, then inheritance is not the right tool for the job.
If you want to read further about the advantages of composition, check this chapter from Effective Java: Favor composition over inheritance
I came across the following Java code that uses generics and inheritance. I truly do not understand what the following snippet does:
class A<B extends A<B>> {
...
}
What does this code do?
(I got this from DBMaker in MapDB)
It is almost clear and the question actually conists in two parts:
1) why B extends A?
2) why A inside B extends A<B> has generic type B?
Answers for these parts will be:
1) In particular example this class (A) is builder class (called DBMaker), so most of its methods return some type, which extends this builder's class type. This explains, why B should extend A class.
2) But, actualy, if we will hide for the second part ...extends A<B>, we will receive just class A<B>. So A has type variable of type B. That is why in ...extends A<B> A is marked as type A having type variable B.
This tells that A needs derived definitions to be able to do some work:
public abstract class A<T extends A<T>> {
protected T instance;
T getOne() {
return instance;
}
}
public class B extends A<B> {
public B() {
instance = this;
}
}
public static void test() {
B b = new B();
b.getOne();
}
This is most commonly used in interface definitions, where one wants to explicitly use instances of classes implementing an interface in return types or in arguments and not the interface itself:
public interface TimeSeries<T extends TimeSeries<T>> {
T join(T ts);
}
public class DoubleTimeSeries implements TimeSeries<DoubleTimeSeries> {
#Override
public DoubleTimeSeries join(DoubleTimeSeries ts) {
return null;
}
}
So I did some tests to figure this one out, and here is my test cases to see how one could use such a generic case:
public class A<B extends A<B>> {
int x = 10;
B test;
void printX() {
System.out.println(x);
}
void setB(B b) {
test = b;
}
void printB() {
System.out.println(test);
}
}
public class B extends A<B> {
}
public class Run {
public static void main(String[] args) {
A<B> test = new A<B>();
B myB = new B();
test.printX();
test.setB(myB);
test.printB();
myB.printB();
}
}
I hope the code might be self explanatory. If not leave a comment and I will try and explain what is going on. Look at the last line, myB.printB(), here we will get a null, because B has not yet been set for myB, but only for test. This demonstrates that we can have an infinite recursion into classes of B inside A (and inside B for that matter).
we can say:
myB.test.printB();
This will get an error (null pointer), but shows that we now have access to test in the A class from B, and we can go as deep as we want recursively with as many cases as we like. So the A class kind of functions as a wrapper of infinitely many B classes. Does this make sense?
This makes it easier when defining method return types such as this:
class A<B extends A<B>> {
public B getMe(){
return (B) this;
}
}
This tells Java compiler that you are in getMe() method returning a subclass of class A.
class C extends A<C> {
}
C c = new C();
c.getMe(); //returns C
Example : How would I make furtherSpecificProcessing method a private method?
Reason: I would like to be able to new an object of type B or C and only have doStuff() visible to programmer. while at the same time class B and C supply the additional functionality
abstract class A
{
protected abstract void furtherSpecificProcessing();
//concrete method utilizing abstract method
public void doStuff()
{
//busy code
furtherSpecificProcessing();
//more busy code
}
public class B extends A
{
public void furtherSpecificProcessing
{
//Class B specific processing
}
}
public class C extends A
{
public void furtherSpecificProcessing
{
//Class C specific processing
}
}
I don't think you can force return type to be private for overriding method.
Access Must not be more restrictive. Can be less restrictive.
I would suggest reading method overriding rules.
Override furtherSpecificProcessing() as protected, not as public in extending classes.
Declare the method as protected instead of public in both classes B and C.
Than what you need will work :
B b = new B();
b.doStuff(); // Will do stuff
b.furtherSpecificProcessing(); // Will not compile
and the same goes for instances of class C
Let's say I have three classes A, B and C.
B extends A
C extends B
All have a public void foo() method defined.
Now from C's foo() method I want to invoke A's foo() method (NOT its parent B's method but the super super class A's method).
I tried super.super.foo();, but it's invalid syntax.
How can I achieve this?
You can't even use reflection. Something like
Class superSuperClass = this.getClass().getSuperclass().getSuperclass();
superSuperClass.getMethod("foo").invoke(this);
would lead to an InvocationTargetException, because even if you call the foo-Method on the superSuperClass, it will still use C.foo() when you specify "this" in invoke. This is a consequence from the fact that all Java methods are virtual methods.
It seems you need help from the B class (e.g. by defining a superFoo(){ super.foo(); } method).
That said, it looks like a design problem if you try something like this, so it would be helpful to give us some background: Why you need to do this?
You can't - because it would break encapsulation.
You're able to call your superclass's method because it's assumed that you know what breaks encapsulation in your own class, and avoid that... but you don't know what rules your superclass is enforcing - so you can't just bypass an implementation there.
You can't do it in a simple manner.
This is what I think you can do:
Have a bool in your class B. Now you must call B's foo from C like [super foo] but before doing this set the bool to true. Now in B's foo check if the bool is true then do not execute any steps in that and just call A's foo.
Hope this helps.
To quote a previous answer "You can't - because it would break encapsulation." to which I would like to add that:
However there is a corner case where you can,namely if the method is static (public or protected). You can not overwrite the static method.
Having a public static method is trivial to prove that you can indeed do this.
For protected however, you need from inside one of your methods to perform a cast to any superclass in the inheritance path and that superclass method would be called.
This is the corner case I am exploring in my answer:
public class A {
static protected callMe(){
System.out.println("A");
}
}
public class B extends A {
static protected callMe(){
System.out.println("B");
}
}
public class C extends B {
static protected callMe(){
System.out.println("C");
C.callMe();
}
public void accessMyParents(){
A a = (A) this;
a.callMe(); //calling beyond super class
}
}
The answer remains still No, but just wanted to show a case where you can, although it probably wouldn't make any sense and is just an exercise.
Yes you can do it. This is a hack. Try not to design your program like this.
class A
{
public void method()
{ /* Code specific to A */ }
}
class B extends A
{
#Override
public void method()
{
//compares if the calling object is of type C, if yes push the call to the A's method.
if(this.getClass().getName().compareTo("C")==0)
{
super.method();
}
else{ /*Code specific to B*/ }
}
}
class C extends B
{
#Override
public void method()
{
/* I want to use the code specific to A without using B */
super.method();
}
}
There is a workaround that solved my similar problem:
Using the class A, B, and C scenario, there is a method that will not break encapsulation nor does it require to declare class C inside of class B. The workaround is to move class B's methods into a separate but protected method.
Then, if those class B's methods are not required simply override that method but don't use 'super' within that method. Overriding and doing nothing effectively neutralises that class B method.
public class A {
protected void callMe() {
System.out.println("callMe for A");
}
}
public class B extends A {
protected void callMe() {
super.callMe();
methodsForB(); // Class B methods moved out and into it's own method
}
protected void methodsForB() {
System.out.println("methods for B");
}
}
public class C extends B {
public static void main(String[] args) {
new C().callMe();
}
protected void callMe() {
super.callMe();
System.out.println("callMe for C");
}
protected void methodsForB() {
// Do nothing thereby neutralising class B methods
}
}
The result will be:
callMe for A
callMe for C
It's not possible, we're limited to call the superclass implementations only.
I smell something fishy here.
Are you sure you are not just pushing the envelope too far "just because you should be able to do it"? Are you sure this is the best design pattern you can get? Have you tried refactoring it?
I had a problem where a superclass would call an top class method that was overridden.
This was my workaround...
//THIS WOULD FAIL CALLING SUPERCLASS METHODS AS a1() would invoke top class METHOD
class foo1{
public void a1(){
a2();
}
public void a2(){}
}
class foo2 extends foo1{
{
public void a1(){
//some other stuff
super.a1();
}
public void a2(){
//some other stuff
super.a2();
}
//THIS ENSURES THE RIGHT SUPERCLASS METHODS ARE CALLED
//the public methods only call private methods so all public methods can be overridden without effecting the superclass's functionality.
class foo1{
public void a1(){
a3();}
public void a2(){
a3();}
private void a3(){
//super class routine
}
class foo2 extends foo1{
{
public void a1(){
//some other stuff
super.a1();
}
public void a2(){
//some other stuff
super.a2();
}
I hope this helps.
:)
Before using reflection API think about the cost of it.
It is simply easy to do. For instance:
C subclass of B and B subclass of A. Both of three have method methodName() for example.
public abstract class A {
public void methodName() {
System.out.println("Class A");
}
}
public class B extends A {
public void methodName() {
super.methodName();
System.out.println("Class B");
}
// Will call the super methodName
public void hackSuper() {
super.methodName();
}
}
public class C extends B {
public static void main(String[] args) {
A a = new C();
a.methodName();
}
#Override
public void methodName() {
/*super.methodName();*/
hackSuper();
System.out.println("Class C");
}
}
Run class C Output will be:
Class A
Class C
Instead of output:
Class A
Class B
Class C
In my simple case I had to inherit B and C from abstract class, that incapsulates equal methods of B and C. So that
A
|
Abstr
/ \
B C
While it doesn't solve the problem, it can be used in simple cases, when C is similar to B. For instance, when C is initialized, but doesn't want to use initializers of B. Then it simply calls Abstr methods.
This is a common part of B and C:
public abstract class Abstr extends AppCompatActivity {
public void showProgress() {
}
public void hideProgress() {
}
}
This is B, that has it's own method onCreate(), which exists in AppCompatActivity:
public class B extends Abstr {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Call from AppCompatActivity.
setContentView(R.layout.activity_B); // B shows "activity_B" resource.
showProgress();
}
}
C shows its own layout:
public class C extends Abstr {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Call from AppCompatActivity.
setContentView(R.layout.activity_C); // C shows "activity_C" resource.
showProgress();
}
}
This is not something that you should do normally but, in special cases where you have to workaround some bug from a third party library (if it allow to do so), you can achieve calling a super super class method that has already been overwritten using the delegation pattern and an inner class that extends the super super class to use as a bridge:
class A() {
public void foo() {
System.out.println("calling A");
}
}
class B extends A() {
#Overwrite
public void foo() {
System.out.println("calling B");
}
}
class C extends B() {
private final a;
public C() {
this.a = new AExtension();
}
#Overwrite
public void foo() {
a.foo();
}
private class AExtension extends A {
}
}
This way you will be able to not only call the super super method but also combine calls to other super super class methods with calls to methods of the super class or the class itself by using `C.super` or `C.this`.