In my application I have a class, let me call it class A. Four classes, let me call them B , C, D and E extend from this class. Each of these four classes has an interface that its functionality is same.
I want to know if I put this interface in class A all of these classes have access to it. Am I right?
I have another class, G that is implementing this interface. If I implement this interface does it apply to those four libraries at same time?
Update
Let me go into detail.
I have four classes. Each class has a method that when this class connects to internet will set a flag. like this.
public class ClassB extends {
public interface OnConnectingToServer {
public void onGettingDataFromServer(boolean flag);
}
public ClassB () {
if(I'm_downloading_from_internet)
OnConnectingToServer.onGettingDataFromServer(true);
}
}
I have this situation for "B", "C", "D" and "E" classes. Class "G", implements this interface. If I want to put each interface in each class therefore, i need to assign four different names ans in "G" class also implements 4 interfaces.
I think this way is not a good way.
I'm looking for a way that instead of implementing 4 same interfaces, implementing just one interface. therefore, regardless of triggering the interface by one class or all four classes, just one implementation is done.
Hope to make it more clear. Thanks again.
Don't put the interface definition inside class A. Make it a separate top-level type and then make all your classes implements MyInterface. If class B extends A, then you don't have to explicitly say implements MyInterface since there is no way for a subclass to "unimplement" an interface.
Yes, if you let A implement an interface, then all classes that extend that class also implement that interface.
Not entirely sure what you mean with letting G implement the interface. Doing that will only affect classes that extend G.
Briefly, yes. From the Java Language Spec:
A class may be declared to directly implement one or more interfaces,
meaning that any instance of the class implements all the abstract
methods specified by the interface or interfaces. A class necessarily
implements all the interfaces that its direct superclasses and direct
superinterfaces do. This (multiple) interface inheritance allows
objects to support (multiple) common behaviors without sharing any
implementation.
(my emphasis)
If you implement the interface (call it I) in class A and B, C + D extend A then B, C and D will implement the I interface as well.
This means you will be able to write:
I aInstance = new A();
I bInstance = new B();
but also:
A aInstance = new A();
A bInstance = new B():
because logically your data model will become:
A is an I
and
B is an A
so this implies:
B is an I
If class G implements the interface but doesn't inherit A you will have to implement the functionality defined in I in the class G as well.
This means you will be able to write:
I aInstance = new A();
I gInstance = new G();
but not this (this won't compile): A gInstance = new G();
Just remember, the interface is only a contract. Any class that implements an interface is bound to respect the contract but no implementation is inherited (no implementation can exist in the interface anyway).
Related
Suppose, I have 2 configurations.
First one:
interface I {
...
}
class A implements I {
...
}
class B implements I {
...
}
class Component {
I i;
Component (I i) {
this.i = i;
}
}
Second one:
class C {
...
}
class A extends C {
...
}
class B extends C {
...
}
class Component {
C c;
Component (C c) {
this.c = c;
}
}
What in the difference between those two configurations which are using two different loose coupling mechanisms (based on interface and based on class)?
Why should I need to use interface over class?
Mainly, using classes is a more heavy approach. Base classes usually contain concrete (non-abstract) methods. And if you derive from them you will need also to inherit such concrete methods, which you may not want.
For example, imagine that you want to benefit from composition design patterns like the decorator pattern. Here, your decorator needs also to derive from the base class and will inherit the concrete methods. However, your decorator will not need the concrete method to function.
In summary, it is more hard/unclean to do object composition if your abstractions are class-based.
Abstraction through interfaces on the other hand, does not force implementing classes to inherit any concrete method implementation. Therefore, it is more clean.
An object can implements multiple interfaces but can only extends one class, so sometimes the user of your loose coupled library may not be able to extends your class.
when you extends, you incorporate the code of the superclass into yours, sometimes there is no code to incorporate so implements is better suited.
Finally it is not the same paradigm, when you write "B extends A" you say "I am A, I do the same things, but I can also make other things". When you write "B implements A" you say "I am B, but you can treat me as an A".
Long story short, the only practical reason would be the first.
A hierarchy based upon interfaces is a good desing approach, because it eases implementation: You can always implement an interface, but not always you can extend a class (for example, a final class). Or, in the other hand, not always a class' author want it to be extended.
So, you are highly interested on using interfaces over classes, because in this way you may accept a wider set of implementations. For example:
Using classes:
class Component
{
AbstractList c;
Component (AbstractList c){...}
}
... Component would accept ArrayList or Vector.
Instead, using interfaces:
class Component
{
List c;
Component (List c){...}
}
... Component would be able to accept ArrayList, Vector, CopyOnWriteArrayList...
Say I have an interface A and a class B that implements it.
Now, I also have some class C which extends class D (which means that it can't also extends B) but I also need there the functionality of interface A.
The solution I know is to have a member of A instantiated by B in C (which will implement A) and when implementing the functions of A call the matching function from the member of A.
Is there any way to create some connection between the functions of A and the member inside C? (so that java will know that every time it needs to call a function from A it will directly go and and run the matching function from the A member without me needing to write the code for it for every function of A)
A big thank you is waiting to each one of the helpers...
No. As already stated delegation must be implemented manually.
Having said that, you have a few options to simplify this: If you're working with Eclipse, select Source|Generate Delegate Methods... and select your member variable. Eclipse will then generate all the delegate methods for you. I don't know about other IDEs, but I would be surprised, if NetBeans et al. would not have a similar feature.
Another option, if you actually want to decorate existing collection classes, consider Google Guava's Google Guava's Collection Helpers.
Last, but not least, you could consider restructing your code and decorate your classes using Advices. Advices stem from Aspect Oriented Programming (AOP) and typically use a proxying mechanism to enrich original target classes. This is a rather advanced technique, but if you are determined to go down this road, have a look at Spring's AOP support.
So to sum up, here is your class hierarchies:
package common;
public interface A
{
void doStuff();
}
package commom.impl;
public class B implements A
{
void doStuff() {}
}
package real.service;
public class D
{
void doSomeRealStuff() {}
}
package real.service;
public class C extends D
{
void doSomeRealStuffForGood() {}
}
Assuming that each class is declared in its own source file.
Just to recall from the OP, I assume you need B stuff in C and not really A stuff. Because A is nothing but a contract and you need then the real implemting class to be fetched inside your C class in order to call the declared methods on.
In such a case, you may need to use the Inversion of Responsability approach, so that you declare an instacne of type B inside your C clas then you layer each method from B with a one having the same signature and that do nothing but delegate the real call to the instance member:
package real.service;
import common.A;
import common.impl.B;
public class C extends D
{
private A delegate;
public C ()
{
delegate = new B();
}
void doStuff() {
delegate.doStuff(); // Call the real delegate method when doStuff is called on an isntance of C.
}
void doSomeRealStuffForGood() {}
}
Note that this is a legal OO concept, since you are following an HAS-a even though some could consider it a high coupling.
Otherwise if you are not tied to the B class, and you may drop the declare methods in there for some others, you can declare an inner class that implements the A interface the way you need.
Edit:
Java does not support multiple inheritance, though you have provided a common contract in your A interface, so if you need all those methods (behavior) to be availble in your C class, it would be better to implement it directely and override all the interface methods.
I know that a class can implement more than one interface, but is it possible to extend more than one class? For example I want my class to extend both TransformGroup and a class I created. Is this possible in Java? Both statements class X extends TransformGroup extends Y and class X extends TransformGroup, Y receive an error. And if it is not possible, why? TransformGroup extends Group but I guess it also extends Node since it inherits fields from Node and it can be passed where a Node object is required. Also, like all classes in Java, they extend Object class. So why wouldn't it be possible to extend with more than one class?
TransformGroup inheritance
So, if that is possible, what is the proper way to do it? And if not, why and how should I solve the problem?
In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies.
Scenario1: As you have learned the following is not possible in Java:
public class Dog extends Animal, Canine{
}
Scenario 2: However the following is possible:
public class Canine extends Animal{
}
public class Dog extends Canine{
}
The difference in these two approaches is that in the second approach there is a clearly defined parent or super class, while in the first approach the super class is ambiguous.
Consider if both Animal and Canine had a method drink(). Under the first scenario which parent method would be called if we called Dog.drink()? Under the second scenario, we know calling Dog.drink() would call the Canine classes drink method as long as Dog had not overridden it.
No it is not possible in java (Maybe in java 8 it will be avilable). Except the case when you extend in a tree.
For example:
class A
class B extends A
class C extends B
In Java multiple inheritance is not permitted for implementations (classes) only for interfaces:
interface A extends B, C
E.g. MouseInputListener extends MouseListener and MouseMotionListener
And, of course, a class can implement several interfaces:
class X implements A, F
Multiple inheritance is not possible with class, you can achieve it with the help of interface but not with class. It is by design of java language. Look a comment by James gosling.
by James Gosling in February 1995 gives an idea on why multiple
inheritance is not supported in Java.
JAVA omits many rarely used, poorly understood, confusing features of
C++ that in our experience bring more grief than beneļ¬t. This
primarily consists of operator overloading (although it does have
method overloading), multiple inheritance, and extensive automatic
coercions.
There is no concept of multiple inheritance in Java. Only multiple interfaces can be implemented.
Assume B and C are overriding inherited method and their own implementation. Now D inherits both B & C using multiple inheritance. D should inherit the overridden method.The Question is which overridden method will be used? Will it be from B or C? Here we have an ambiguity. To exclude such situation multiple inheritance was not used in Java.
Java didn't provide multiple inheritance.
When you say A extends B then it means that A extends B and B extends Object.
It doesn't mean A extends B, Object.
class A extends Object
class B extends A
java can not support multiple inheritence.but u can do this in this way
class X
{
}
class Y extends X
{
}
class Z extends Y{
}
Most of the answers given seem to assume that all the classes we are looking to inherit from are defined by us.
But what if one of the classes is not defined by us, i.e. we cannot change what one of those classes inherits from and therefore cannot make use of the accepted answer, what happens then?
Well the answer depends on if we have at least one of the classes having been defined by us. i.e. there exists a class A among the list of classes we would like to inherit from, where A is created by us.
In addition to the already accepted answer, I propose 3 more instances of this multiple inheritance problem and possible solutions to each.
Inheritance type 1
Ok say you want a class C to extend classes, A and B, where B is a class defined somewhere else, but A is defined by us. What we can do with this is to turn A into an interface then, class C can implement A while extending B.
class A {}
class B {} // Some external class
class C {}
Turns into
interface A {}
class AImpl implements A {}
class B {} // Some external class
class C extends B implements A
Inheritance type 2
Now say you have more than two classes to inherit from, well the same idea still holds - all but one of the classes has to be defined by us. So say we want class A to inherit from the following classes, B, C, ... X where X is a class which is external to us, i.e. defined somewhere else. We apply the same idea of turning all the other classes but the last into an interface then we can have:
interface B {}
class BImpl implements B {}
interface C {}
class CImpl implements C {}
...
class X {}
class A extends X implements B, C, ...
Inheritance type 3
Finally, there is also the case where you have just a bunch of classes to inherit from, but none of them are defined by you. This is a bit trickier, but it is doable by making use of delegation. Delegation allows a class A to pretend to be some other class B but any calls on A to some public method defined in B, actually delegates that call to an object of type B and the result is returned. This makes class A what I would call a Fat class
How does this help?
Well it's simple. You create an interface which specifies the public methods within the external classes which you would like to make use of, as well as methods within the new class you are creating, then you have your new class implement that interface. That may have sounded confusing, so let me explain better.
Initially we have the following external classes B, C, D, ..., X, and we want our new class A to inherit from all those classes.
class B {
public void foo() {}
}
class C {
public void bar() {}
}
class D {
public void fooFoo() {}
}
...
class X {
public String fooBar() {}
}
Next we create an interface A which exposes the public methods that were previously in class A as well as the public methods from the above classes
interface A {
void doSomething(); // previously defined in A
String fooBar(); // from class X
void fooFoo(); // from class D
void bar(); // from class C
void foo(); // from class B
}
Finally, we create a class AImpl which implements the interface A.
class AImpl implements A {
// It needs instances of the other classes, so those should be
// part of the constructor
public AImpl(B b, C c, D d, X x) {}
... // define the methods within the interface
}
And there you have it! This is sort of pseudo-inheritance because an object of type A is not a strict descendant of any of the external classes we started with but rather exposes an interface which defines the same methods as in those classes.
You might ask, why we didn't just create a class that defines the methods we would like to make use of, rather than defining an interface. i.e. why didn't we just have a class A which contains the public methods from the classes we would like to inherit from? This is done in order to reduce coupling. We don't want to have classes that use A to have to depend too much on class A (because classes tend to change a lot), but rather to rely on the promise given within the interface A.
Java does not allow extending multiple classes.
Let's assume C class is extending A and B classes. Then if suppose A and B classes have method with same name(Ex: method1()). Consider the code:
C obj1 = new C();
obj1.method1(); - here JVM will not understand to which method it need to access. Because both A and B classes have this method. So we are putting JVM in dilemma, so that is the reason why multiple inheritance is removed from Java. And as said implementing multiple classes will resolve this issue.
Hope this has helped.
Hello please note like real work.
Children can not have two mother
So in java, subclass can not have two parent class.
Is it really necessary to implement all the methods to a subclass(inherited from a abstract class), if there is another subclass of that abstract class has already implemented those abstract methods?
abstract class A {
abstract void method();
abstract void anothermethod();
}
class B extends A {
void method() {}
void anothermethod() {}
}
class C extends A { // is this class definition is legal?
void sample() {}
}
Only if you mark C as an abstract class. Therefore passing on its implementation responsibilities to it's subclasses.
Another option would be to have C extend B, and therefore B would contain the implementation demanded of A by its subclasses.
No, it's not legal. You've got a concrete class (C is not declared abstract) extending an abstract class, but without providing implementations for its methods. It's not really clear why you think this should or could be legal - and you should consider whether this has wider ramifications for your understanding of inheritance in general than just this specific case.
C is entirely separate from B. They could have entirely different state - for example, B might implement method() using some state which is only present in an instance of B. It's important to understand that an instance of C is not an instance of B.
If you want it to inherit its behaviour, you should make C subclass B instead of A.
No. Class C will be abstract in this case, too.
What about class C extends B?
Thats absolutely illegal unless you make the class "C" abstract as IronBlossom suggested or implements all the abstract method of class "A"in class "C".
Suppose I have class hierarchy like the one shown in picture. Suppose I need to include a method doThis() that would have different implementation in classes C and D. But the class B need not implement this method.
Should I declare the contract in Class A and provide an empty implementation in class B or have another abstract class X which extends A and is being extended by C and D?
Thanks
Do not put it into class A. Use an interface that is implemented by those that need it.
If only sub-classes of A will use the method:
Make another abstract class that extend A and adds the method.
If you intend to have that method implemented in different class types:
Make an interface that declares the method, and then C,D should implement that interface as well.
Make an interface called "doable". let your classes C and D implement this.
public interface Doable {
public void doThis();
}
public class D implements Doable { /*implementations*/ }
public class C implements Doable { /*implementations*/ }
Do not put it in A if you can avoid it.
The best solution can not be determined from the information you have given us. It depends on the context and meaning of the classes and methods.