class and interface
I wonder 3 things.
1: If I have implemented an interface (with a method) in a superclass where im declaring that method, and then I extend that superclass in another class. Then I don't have to redeclare that method right?
2: But if I don't declare that method in the superclass but in the child class then I instantiate the superclass. What happens then? It didn't contain an开发者_运维问答y method from the instance.
3: Could you use implement in a class and then not declaring that method? Maybe it will be used as a superclass only for other classes to extend. And then just declare that method in the child classes or do you have to declare it in the current class you are implementing the interface?
Assuming you meant "reimplement" instead of "redeclare", that's correct.
Depends whether the class is declared abstract or not. If the superclass is abstract, then the child class either needs to implement it or to be declared abstract as well. If the superclass is not abstract, then it won't compile.
Declare the class abstract if you don't want to implement it.
More on this subject on Sun tutorial about interfaces and inheritance.
This is tagged for both PHP and Java - I'll answer for Java.
Right, it will inherit the implementation of the method from the superclass.
If the superclass still is declared as implementing the interface then it will cause a compile-time error, so this is not possible.
No, as I said before, if you implement an interface then you must implement or inherit the methods that that interface declares. The only exception is if the class is
abstract
, in which case you do not need to provide an implementation for the interface methods (which are implicitlyabstract
). Abstract classes cannot be instantiated.
Just adding to what has been already answered for the 2nd question (for Java):
As mentioned in other answer (by @BalusC), if your superclass tells that it implements an interface and doesn't provide implementation of method(s) in the interface then you have to mark the superclass as an abstract class. But you cannot instantiate
the superclass since it is an abstract class.
精彩评论