For example, I have an interface with 4 methods.
If I implement this interface incomplete in a class, the class must be abstract. Right?
For example, I leave one method out. So now I am writing a subclass which extends this class. Now I implement the last method of the interface.
What happens, if I call this method in the abstract superclass? Nothing! It works. But why?
What will happen, if I write several classes, extending this abstract class and implement the fourth method of the interface? Which one will be called?
A interface is a contract you define the signature of your methods, only behaviour and constants, all methods are public and abstract.
In an Abstract Class you define behaviour and state, you can have some implementation and abstract methods.
For example for your question:
If I implement this interface incomplete in a class, the class must be abstract. Right?
Right
For example, I leave one method out. So now I am writing a subclass which extends this class. Now I implement the last method of the interface.
What happens, if I call this method in the abstract superclass? Nothing! It works. But why?
Will run cause in runtime execution knows what class is. this is polymorphism.
What will happen, if I write several classes, extending this abstract class and implement the fourth method of the interface. Which one will be called?
The one you instanciate in your client code :D
public interface Operation{
void operation1();
void operation2();
}
I don't implement operation2
public abstract class ClaseBase implements Operation{
//with final im saying childs wont override
public final void operation1{
// do something
operation2();
// do something
}
}
//have to implements operation2 cause it's a concrete class
public class Child extends ClaseBase{
void operation2(){
System.out.println("Something");
}
}
You can't instanciate an AbstractClass.
In your client code
ClaseBase base = new Child();
base.operation1(); // and it's gonna to call operation2 in childClass
Abstract class is useful with Template Method pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With