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.
Related
I am new to Java, coming from a C++ background and I try to understand the concept of interface and abstract class implementing an interface. What exactly happens when an abstract class implements an interface? Does this work like inheritance, i.e. all interface methods belong also to the abtract class eventhough they are not implemented in it? Or will only the implemented methods belong to the abstract class? So is there any difference between implements and extends, except that one is used to implement interfaces and the other one is used for inheritance?
You can imagine an abstract class as an unfinished class. It's like a template for actual real classes. Interfaces are mainly used to describe properties, like CanWalk, IsCloseable, HasAName and so on.
There is no big difference between both concepts from the language perspective, other than that you can only extend from one class but are allowed to implement multiple interfaces.
In the end of the inheritance chain you will always have non-abstract concrete classes. Which is obvious, you can't use unfinished classes in the end, you need to finish them. That's why
Animal animal = new Animal();
does not work if Animal is abstract. We need to create instances of finished classes, like a Dog who extends from Animal.
And at that point, where you have a finished (non-abstract) class, all abstract methods need to be implemented. It doesn't matter from where those methods come from, abstract classes or interfaces, they need to be implemented.
So if you have an abstract class and implement an interface with it, you have two options for the interface methods. You either
implement them in the abstract class or
you leave them abstract, but then some of your more concrete children need to implement it.
Example
Let's suppose we have an interface like
public interface CanMakeNoise {
void makeNoise();
}
and the abstract class
public abstract class Animal implements CanMakeNoise {
public abstract void jump();
...
}
together with a concrete extending class
public class Dog extends Animal {
...
}
Since Dog is not abstract, all methods need to be implemented. That is, we need implementations for jump and makeNoise. For the makeNoise method we have two options, either Animal implements it or it leaves it abstract, then Dog needs to implement it:
// Variant 1
public abstract class Animal implements CanMakeNoise {
public abstract void jump();
#Override
public void makeNoise() {
System.out.println("hello, what's up");
}
}
or
// Variant 2
public abstract class Animal implements CanMakeNoise {
public abstract void jump();
}
public class Dog extends Animal {
#Override
public void makeNoise() {
System.out.println("Wuff wuff");
}
}
And of course Dog needs to implement jump:
public class Dog extends Animal {
#Override
public void jump() {
System.out.println("Boing");
}
...
}
In this case it's probably better to leave the implementation of makeNoise up to more concrete classes since Animal has no clue how a specific animal will sound like.
Extending the example, if you have even more concrete classes like a Chihuahua extends Dog, you could implement the makeNoise in Dog since all dogs do "Wuff, wuff".
A method belongs to implementing class of course. I won't say that it doesn't matter where it comes from because of polymorphism. In Java you don't have multi-inheritance but you can implement multiple interfaces, so this is giving you more options about the hierarchy.
In Java, a class can only inherit from one class, but can implements multiple interfaces.
An abstract class is very similar to an interface. The main difference is that an abstract class can define some function already, an interface can’t (note that this changed in Java9+).
Which one to use? Well it really depends on your structure but the javadoc defines some exemple.
If you are worried about the usage of the interface then it will be used for callbacks as Java don't support function pointers.
According to this document, and many similar documents, a concrete class is described as:
A concrete class in Java is any such class which has implementation of all of its inherited members either from interface or abstract class
And can used like this:
public abstract class A {
public abstract void methodA();
}
interface B {
public void printB();
}
public class C extends A implements B {
public void methodA() {
System.out.print("I am abstract implementation");
}
public void printB() {
System.out.print("I am interface implementation");
}
}
In the above example class C is a concrete class.
Is this the only way to create a concrete class. Can you give me more info about concrete class?
A concrete class is a class that has an implementation for all of its methods that were inherited from abstract or implemented via interfaces. It also does not define any abstract methods of its own. This means that an instance of the class can be created/allocated with the new keyword without having to implement any methods first. Therefore it can be inferred that any class that is not an abstract class or interface is a concrete class.
In your code above, C will be a concrete class as it implements all abstract methods inherited from A and implemented from B. Also, it does not define any abstract methods of its own.
The simplest definition of a concrete class is that it's a class that is not abstract.
As per name suggests, concrete means Solid, it means having no any row part or unimplemented things(methods).So we can conclude that concrete classes are those classes that can be instantiated with new key word.
MyClass myClass = new MyClass();
1.concrete class is a class which can never become
an abstract or interface .It can extend or implement or both.
2.The class is said to be concrete if all its methods and variables has defined.
A concrete class in Java is any such class which has implementation of all of its inherited members either from interface or abstract class
In the above program, representing abstract as public class will sometimes show some compile time errors to define that in its own file. As simple, just avoid using public keyword or modifier while using abstract class in your program to avoid some uncertainty. Any method that is invoked using new keyword (object creation) other than abstract and interface classes is called as concrete 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)
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,
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.