interface Bouncable{ } interface Colorable extends Bouncable{ } class Super implements Colorable{ } class Sub extends Super implements Colorable {} // Ok (case -1)
But,
class Sub implements Colorable extends Super {} // error (case -2)
Why case-2 showing compilation error { expected
. Why ?? Although, case-1 executes without error.
Difference: implements means you are using the elements of a Java Interface in your class. extends means that you are creating a subclass of the base class you are extending. You can only extend one class in your child class, but you can implement as many interfaces as you would like.
An interface can extend any number of interfaces. An interface can never implement any other interface.
Yes, you can. But you need to declare extends before implements : public class DetailActivity extends AppCompatActivity implements Interface1, Interface2 { // ... }
extends
should go before implements
:
class Sub extends Super implements Colorable {}
I have an example to show why extends precedes implements in class declaration,
inerface :
public interface IParent { void getName(); void getAddress(); void getMobileNumber(); }
abstract class :
public abstract class Parent { public abstract void getAge(); public void getName(){ System.out.print("the parent name"); } }
Child class :
public class Child extends Parent implements IParent { @Override public void getAddress() { System.out.print(" Child class overrides the Parent class getAddress()"); } @Override public void getMobileNumber() { System.out.print(" Child class overrides the Parent class getMobileNumber()"); } @Override public void getAge() { //To change body of implemented methods use File | Settings | File Templates. } }
If you observe there is same method getName() in both interface and in abstract class, where in abstract class the method has the implementation.
When you try to implement, then it's mandatory for a class to override all the abstract methods of an interface and then we are trying to extend the abstract class which has already has an implementation for the method getName().
when you create an instance of a Child class and called the method getName() as
Child child = new Child(); child.getName();
There will a conflict for a child to call which method implementation as there will be two implementation for the same method getName().
To avoid this conflict they made it mandatory to extend first and implement an interface later.
so if an abstract class has the same method as in an interface and if abstract class has implemented the method already then for a child class its not necessary to override that method
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