I have several classes implements interface MyInterface and I want all of them to extend abstract class MyAbstractClass. What is the best way to do that?
Is there any better way than create another abstract class extending MyAbstractClass and implementing MyInterface?
(I swear I haven't found any question like this before I posted)
The cleanest solution would be to define such a requirement in the JavaDoc of the interface. In the JavaDoc it should then state something like "to use this interface you need to extend from MyAbstractClass or provide your own implementation". This way the programmer is responsible for the implementation. Remember that this is a sociological problem which you try to solve technicality.
Another 'solution' would be to drop the interface and use an abstract class. Implementing the interface in the abstract class wouldn't make sense here.
You could define MyAbstractClass to implement MyInterface, and then make all of your other classes extend MyAbstractClass:
public abstract class MyAbstractClass implements MyInterface {
...
}
public class OneOfSeveral extends MyAbstractClass {
...
}
You can't force all your concrete classes to extend MyAbstractClass in any other way than actually changing their definitions from
class A implements MyInterface
to
class A extends MyAbstractClass
and of course
abstract class MyAbstractClass implements MyInterface
You don't need another abstract class as you write, though.
Edit: Regarding your comment below: "I want the other way that every implementation of MyInterface extends MyAbstractClass" - you cannot enforce that sensibly. You can define another interface that MyInterface extends and call that MyAbstractClassInterface if you want but you still won't be able to enforce your existing classes extend an abstract class implementing this latter interface, although they will of course have to actually implement the methods defined in this interface...
It sounds to me that you should drop the interface and replace it with the abstract class.
Cheers,
Related
While developing some demo application, I came accross a situation like below.
I have basically 3 classes among others:
-One interface MyInterface
-One base class MyBaseClass
-One derived class MyDerivedClassExtendsMyBaseClass
In this structure, MyBaseClass implements MyInterface. Java forces me to implement the methods of MyInterface in the MyBaseClass.
When MyDerivedClassExtendsMyBaseClass also implements MyInterface, Java does not force me to implement the methods of MyInterface. It is up to me to override MyInterface methods.
public interface MyInterface{
public void myMethod();
}
public class MyBase implements MyInterface{
//some members and methods here
#Override
public void myMethod(){
//You have to implement myMethod
}
}
public class MyDerivedClassExtendsMyBaseClass extends MyBase implements MyInterface{
//You don't have to implement myMethod() here!!
}
Is there a special purpose for this? Why I don't have to implement the method of interface MyInterface although my derived class implements it?
Thanks!
Because your Derived Class extending MyBase Class and it has already forced to implement methods of MyInterface. Since Derived class is a child of MyBase , it can inherit from super class, hence there is no need of implement them again. There is always an implementation for it (right now from parent).
If you remove the extends, again you will be forced to implement in derived class.
I am trying to use extends keyword in place of implement to use interface is it possible in java.
Interface myinterface
{
//methods
}
public class myclass extends myinterface
{
//methods
}
Tell me the purpose of these two words extends and implements. why class is not use implement keyword to inherits the class from other class
Think about the two words and what they are telling you.
Implements - means to put something into effect. An interface is regularly defined as a contract of what methods a class must have, or implement. Essentially you are putting that contract into effect.
Extends - means to make longer. By extending the class you are basically making it longer by also including all the methods of the extended class.
Two different words that are giving you, by definition, two different abilities within your code.
Interface cannot be extended but rather implemented.
Interfaces can contain only constants, method signatures, and nested types. That is they only represent an abstraction of your model or can simply contain a list of constants.
Interfaces support inheritance. You can have for instance :
public interface InterfaceA extends InterfaceB
If you really want to extend from a class and have some abstract methods you can use an abstract class as :
public abstract class AbstractA {
public abstract void myAbstractMethod;
}
public class A extends AbstractA {
#Override
public abstract void myAbstractMethod {
// your code
}
}
No, you have to use implements with interfaces.
You can however make an abstract class if you absolutely need to use extend.
Classes cannot extend an Interface. They can only implement them. Only an Interface can extend another Interface just like only a Class can extend another Class.
Tell me the purpose of these two words extends and implements.
When a class extends it inherits attributes and behaviour i.e. methods from the class it extends from. A class can only extend from one class since multiple inheritance isn't supported in Java.
When a class implements it provides behaviour i.e. implementation for the methods defined as stubs (just the signature without code) in the Interface it implements. A class can however implement multiple interfaces.
When an Interface extends another Interface its simply adding more methods to the list of methods that a Class implementing it needs to provide implementation for.
As others, most succinctly #Stefan Beike, have said: no, you can't use extends when you mean implements. What you can do, if desired, is to add an in-between abstract class which implements your interface, and then extend that class. Sometimes this is done with empty implementations of the interface's methods, and then you only need to override the methods of interest in your child class. But it can be a purely abstract class if all you want is to use extends where implements would otherwise be called for.
Extends - is used by a class for extending some features of another class, so that same method or fields can be reused. Basic example can be :
class Animal
{
private String name;
public void setName(String name)
{
this.name = name;
}
public int getLegs()
{
return 2;
}
}
class Elephant extends Animal
{
public int getLegs()
{
return 4;
}
}
Now, setter is reused and extends doesn't mandate it to be overriden, but as per requirement any method can be overriden also, as getter in our case.
Implements - A class can implement an interface. This helps in achieving abstraction. any method in interface needs to be implemented by any class that is implementing the interface. It is mandatory, until or unless class is abstract, in which case any other concrete class should implement the unimplemented methods.
So, a class can extends other class for reusing functionality, and a class can implement an interface to enforce some functionality that a class must provide by itself.
Now, why interface extends interface, I am also not sure, may be its because sub interface will extend the methods of super interface and it will enforce implementation of methods in super interface on class that is implementing the sub interface. As super interface does not enforce implementation on sub interface, so implements can not be used.
I hope I am clear.
class extends class (Correct)
class extends interface (Incorrect) => class implements interface (Correct)
interface extends interface (Correct)
interface extends class (Incorrect) (Never possible)
Why an abstract class that implements an interface has not the necessity to implements interface's methods while instead a class has the necessity to implements all the methods?
Since an abstract class leaves the implementation of one or more of it's methods to it's extending classes, it can do the same with the method contracts it inherits through implementing additional interfaces.
It is not necessary that class has to implements all the methods of an implemented interface. If class don't implement all the methods of an interface it can be declared as abstract class.
Abstract class, by definition, is a class that can have unimplemented methods. If an abstract class implements an interface, it is not bound to implement any of the the inherited methods. That doesn't mean you can't implement any of them. :D
Ultimately we have to create a concrete class. Only then we are going to create an instance and use it. Moreover after implementing an interface an abstract class won't become a concrete class but if a concrete class leaves a method unimplemented it must become an abstract class.
What I mean is:
interface B {...}
interface A extends B {...} // allowed
interface A implements B {...} // not allowed
I googled it and I found this:
implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible.
However, interface is an 100% abstract class, and an abstract class can implement interfaces (100% abstract class) without implement its methods. What is the problem when it is defining as "interface" ?
In details,
interface A {
void methodA();
}
abstract class B implements A {} // we may not implement methodA() but allowed
class C extends B {
void methodA(){}
}
interface B implements A {} // not allowed.
//however, interface B = %100 abstract class B
implements means implementation, when interface is meant to declare just to provide interface not for implementation.
A 100% abstract class is functionally equivalent to an interface but it can also have implementation if you wish (in this case it won't remain 100% abstract), so from the JVM's perspective they are different things.
Also the member variable in a 100% abstract class can have any access qualifier, where in an interface they are implicitly public static final.
implements means a behaviour will be defined for abstract methods (except for abstract classes obviously), you define the implementation.
extends means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends another interface instead of implementing it.
On a side note, remember that even if an abstract class can define abstract methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.
However, interface is 100% abstract class and abstract class can
implements interface(100% abstract class) without implement its
methods. What is the problem when it is defining as "interface" ?
This is simply a matter of convention. The writers of the java language decided that "extends" is the best way to describe this relationship, so that's what we all use.
In general, even though an interface is "a 100% abstract class," we don't think about them that way. We usually think about interfaces as a promise to implement certain key methods rather than a class to derive from. And so we tend to use different language for interfaces than for classes.
As others state, there are good reasons for choosing "extends" over "implements."
Hope this will help you a little what I have learned in oops (core java) during my college.
Implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible. An interface can however extend another interface, which means it can add more methods and inherit its type.
Here is an example below, this is my understanding and what I have learnt in oops.
interface ParentInterface{
void myMethod();
}
interface SubInterface extends ParentInterface{
void anotherMethod();
}
and keep one thing in a mind one interface can only extend another interface and if you want to define it's function on some class then only a interface in implemented eg below
public interface Dog
{
public boolean Barks();
public boolean isGoldenRetriever();
}
Now, if a class were to implement this interface, this is what it would look like:
public class SomeClass implements Dog
{
public boolean Barks{
// method definition here
}
public boolean isGoldenRetriever{
// method definition here
}
}
and if a abstract class has some abstract function define and declare and you want to define those function or you can say implement those function then you suppose to extends that class because abstract class can only be extended. here is example below.
public abstract class MyAbstractClass {
public abstract void abstractMethod();
}
Here is an example subclass of MyAbstractClass:
public class MySubClass extends MyAbstractClass {
public void abstractMethod() {
System.out.println("My method implementation");
}
}
Interface is like an abstraction that is not providing any functionality. Hence It does not 'implement' but extend the other abstractions or interfaces.
Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.
This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Abstract class vs Interface in Java
(15 answers)
Closed 2 years ago.
Please tell me situation where interface is better than abstract class in Java
I think you have misunderstood the real meaning of interface and abstract class.
Interface is programming structure where you define your functions/services that you want to expose to public or other modules. Kind of a contract where you promise that you are providing some functionalities or services, but hiding the implementation so that implementation can be changed without affecting your contract.
Abstract class is a partially implemented class and it has no real meaning other than serving as a parent for multiple child classes those with real meaning. Abstract class is special parent class that provides default functionalities to multiple child classes. it is created as abstract because of unavailability of suitable concrete parent class.
In a good design, you should always create an interface. But abstract class is optional. If you can not find a concrete parent class, create an abstract class and implement the interface then provide default implementations for those interface functions (if possible) otherwise mark them as abstract functions and leave the implementation to the child classes.
A class can implement multiple interfaces, but it can only extend one abstract class.
Interfaces allow the creation of proxies that encapsulate a concrete class. This is used extensively by frameworks in order to intercept method calls to the concrete class (e.g., for starting a transaction before the method is executed or to write to the log).
Use an interface when you don't need to provide any default implementations.
Here is a nice link comparing the two: Interface vs. Abstract Class
You can only have one direct abstract superclass. Therefore, interfaces are useful if you need to expose two or more interfaces.
Java doesn't have multiple inheritance; thus, you cannot have a class that implements two abstract classes at once. For instance, if you want a MouseListener and an ActionListener in a same class, you have to do it the interface way.
An interface is better than a abstract class when you want multiple classes to implement that interface and when you don't have to inherit default behavior.
In order to provide WebServices or do JMock tests you dont need the actual implementation, you just need an interface definition. Think about it, there is no need to return the implementation to a third party when all they need to do is call your API.
When you need to implements in any class because interface can be implements in any class or interface but abstract class cant do that e.g. in Applet always Applet class extend in our Applet Application in this case we cant extend the abstract class.
Abstract Class : Define or Declare a method which is more important. Example:
Vehicle must have shape and engine. So we put this behaviour is in Abstract class.
abstract class Vehicle {
abstract void shape();
abstract void engine();
}
Interface Class : Other than that properties like move, honk, etc. So interfaces that provide additional behaviour to your concrete class.
interface Honk{
void honk();
}
interface moveable{
void move();
}
class Car extends Vehicle implements Moveable {
#Override
void shape() {
System.out.println("car's shape");
}
#Override
void Engine() {
System.out.println("car's engine");
}
#Override
void move() {
System.out.println("car's can move");
}
}
But I didn't implements Honk behaviour. If you want you can implements multiple interfaces.