Reputation: 303
I was just wondering why an abstract
class can't extend an interface
.
Since we can't instantiate an abstract
class, can't I just extend the interface and then override those methods in the classes which are extending the abstract class?
For example
abstract class AbstractClass extends InterfaceA
{
}
interface InterfaceA
{
public void methodToBeImplemented();
}
class MyClass extends AbstractClass
{
@Override
public void methodToBeImplemented(){
//do something
}
}
Upvotes: 13
Views: 22674
Reputation: 15103
Because you don't extends
an interface - you implements
it.
interface InterfaceA
{
public void methodToBeImplemented();
}
abstract class AbstractClass implements InterfaceA
{
}
class MyClass extends AbstractClass
{
@Override
public void methodToBeImplemented(){
//do something
}
}
An abstract class is still a class, just like any other. Only interfaces can extends
other interfaces.
Upvotes: 24
Reputation: 11
in interface extends only interface .when we use a interface in a class then it need to implements in class.and another thing is abstract class contain a both abstract and non abstract method while interface contain only abstract method that are define where implementation of inteface(subclass).
Upvotes: 1
Reputation: 1748
You can actually extend interfaces in Java, but it would still be called an interface.
Then you can use this extended interface implemented in your abstract class.
interface InterfaceName
{
public void foo();
}
public interface ExtendedInterface extends InterfaceName
{
public void bar();
}
public class ClassName implements ExtendedInteface
{
//implementation for all methods in InterfaceName and ExtendedInteface
...
}
Praveen, its just the way the designers designed it. It goes back to the philosophy of Java and the way classes and interfaces are meant to be used. Lets say you have following classes: Student, Professor, Employee, Technician. And following interfaces: Demography, Paydetails and Personaldetails.
Ideally, classes professor and technician can be both extended from the class employee and it makes sense. However, imagine extending class Technician from Demography or Personaldetails. It doesnt make sense. Its like extending class sky from class blue. Just cause you can do doesnt mean you should do it. However, it makes more sense to have a class technician extend from employee and implement interfaces like Paydetails or demography. Its like extending sky from nature but implementing interface blue (giving it function capabilities of blue).
This is the basic reason why Java developers were against multiple inheritance (unlike cpp) and instead use interfaces. In your question, it doesnt matter if the class is abstract or not. You simple cant extend from an interface cause it does not make sense logically.
Upvotes: 5