Implements vs extends: When to use? What's the difference?

前端 未结 18 608
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 17:03

Please explain in an easy to understand language or a link to some article.

相关标签:
18条回答
  • 2020-11-22 17:10

    When a subclass extends a class, it allows the subclass to inherit (reuse) and override code defined in the supertype. When a class implements an interface, it allows an object created from the class to be used in any context that expects a value of the interface.

    The real catch here is that while we are implementing anything it simply means we are using those methods as it is. There is no scope for change in their values and return types.

    But when we are extending anything then it becomes an extension of your class. You can change it, use it, reuse use it and it does not necessarily need to return the same values as it does in superclass.

    0 讨论(0)
  • 2020-11-22 17:10

    Extends is used when you want attributes of parent class/interface in your child class/interface and implements is used when you want attributes of an interface in your class.

    Example:

    1. Extends using class

      class Parent{

      }

      class Child extends Parent{

      }

    2. Extends using interface

      interface Parent{

      }

      interface Child extends Parent{

      }

    3. Implements

    interface A{

    }

    class B implements A{

    }

    Combination of extends and implements

    interface A{
    
    }
    
    class B
    
    {
    
    }
    
    class C implements A,extends B{
    
    }
    
    0 讨论(0)
  • 2020-11-22 17:13

    We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.

    Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.

    Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.

    But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks. But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.

    So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.

    So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.

    You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).

    I will share with you a piece of code: You try it with different sets of inputs and look at the results.

    class AnimalClass {
    
    public void doEat() {
        
        System.out.println("Animal Eating...");
    }
    
    public void sleep() {
        
        System.out.println("Animal Sleeping...");
    }
    
    }
    
    public class Dog extends AnimalClass implements AnimalInterface, Herbi{
    
    public static void main(String[] args) {
        
        AnimalInterface a = new Dog();
        Dog obj = new Dog();
        obj.doEat();
        a.eating();
        
        obj.eating();
        obj.herbiEating();
    }
    
    public void doEat() {
        System.out.println("Dog eating...");
    }
    
    @Override
    public void eating() {
        
        System.out.println("Eating through an interface...");
        // TODO Auto-generated method stub
        
    }
    
    @Override
    public void herbiEating() {
        
        System.out.println("Herbi eating through an interface...");
        // TODO Auto-generated method stub
        
    }
    
    
    }
    

    Defined Interfaces :

    public interface AnimalInterface {
    
    public void eating();
    
    }
    
    
    interface Herbi {
    
    public void herbiEating();
    
    }
    
    0 讨论(0)
  • 2020-11-22 17:13

    extends

    • class extends only one class
    • interface extends one or more interfaces

    implements

    • class implements one or more interfaces
    • interfaces 'can not' implements anything

    abstract classes also act like class, with extends and implements

    0 讨论(0)
  • 2020-11-22 17:14

    Generally implements used for implementing an interface and extends used for extension of base class behaviour or abstract class.

    extends: A derived class can extend a base class. You may redefine the behaviour of an established relation. Derived class "is a" base class type

    implements: You are implementing a contract. The class implementing the interface "has a" capability.

    With java 8 release, interface can have default methods in interface, which provides implementation in interface itself.

    Refer to this question for when to use each of them:

    Interface vs Abstract Class (general OO)

    Example to understand things.

    public class ExtendsAndImplementsDemo{
        public static void main(String args[]){
    
            Dog dog = new Dog("Tiger",16);
            Cat cat = new Cat("July",20);
    
            System.out.println("Dog:"+dog);
            System.out.println("Cat:"+cat);
    
            dog.remember();
            dog.protectOwner();
            Learn dl = dog;
            dl.learn();
    
            cat.remember();
            cat.protectOwner();
    
            Climb c = cat;
            c.climb();
    
            Man man = new Man("Ravindra",40);
            System.out.println(man);
    
            Climb cm = man;
            cm.climb();
            Think t = man;
            t.think();
            Learn l = man;
            l.learn();
            Apply a = man;
            a.apply();
    
        }
    }
    
    abstract class Animal{
        String name;
        int lifeExpentency;
        public Animal(String name,int lifeExpentency ){
            this.name = name;
            this.lifeExpentency=lifeExpentency;
        }
        public void remember(){
            System.out.println("Define your own remember");
        }
        public void protectOwner(){
            System.out.println("Define your own protectOwner");
        }
    
        public String toString(){
            return this.getClass().getSimpleName()+":"+name+":"+lifeExpentency;
        }
    }
    class Dog extends Animal implements Learn{
    
        public Dog(String name,int age){
            super(name,age);
        }
        public void remember(){
            System.out.println(this.getClass().getSimpleName()+" can remember for 5 minutes");
        }
        public void protectOwner(){
            System.out.println(this.getClass().getSimpleName()+ " will protect owner");
        }
        public void learn(){
            System.out.println(this.getClass().getSimpleName()+ " can learn:");
        }
    }
    class Cat extends Animal implements Climb {
        public Cat(String name,int age){
            super(name,age);
        }
        public void remember(){
            System.out.println(this.getClass().getSimpleName() + " can remember for 16 hours");
        }
        public void protectOwner(){
            System.out.println(this.getClass().getSimpleName()+ " won't protect owner");
        }
        public void climb(){
            System.out.println(this.getClass().getSimpleName()+ " can climb");
        }
    }
    interface Climb{
        public void climb();
    }
    interface Think {
        public void think();
    }
    
    interface Learn {
        public void learn();
    }
    interface Apply{
        public void apply();
    }
    
    class Man implements Think,Learn,Apply,Climb{
        String name;
        int age;
    
        public Man(String name,int age){
            this.name = name;
            this.age = age;
        }
        public void think(){
            System.out.println("I can think:"+this.getClass().getSimpleName());
        }
        public void learn(){
            System.out.println("I can learn:"+this.getClass().getSimpleName());
        }
        public void apply(){
            System.out.println("I can apply:"+this.getClass().getSimpleName());
        }
        public void climb(){
            System.out.println("I can climb:"+this.getClass().getSimpleName());
        }
        public String toString(){
            return "Man :"+name+":Age:"+age;
        }
    }
    

    output:

    Dog:Dog:Tiger:16
    Cat:Cat:July:20
    Dog can remember for 5 minutes
    Dog will protect owner
    Dog can learn:
    Cat can remember for 16 hours
    Cat won't protect owner
    Cat can climb
    Man :Ravindra:Age:40
    I can climb:Man
    I can think:Man
    I can learn:Man
    I can apply:Man
    

    Important points to understand:

    1. Dog and Cat are animals and they extended remember() and protectOwner() by sharing name,lifeExpentency from Animal
    2. Cat can climb() but Dog does not. Dog can think() but Cat does not. These specific capabilities are added to Cat and Dog by implementing that capability.
    3. Man is not an animal but he can Think,Learn,Apply,Climb

    By going through these examples, you can understand that

    Unrelated classes can have capabilities through interface but related classes override behaviour through extension of base classes.

    0 讨论(0)
  • 2020-11-22 17:16

    I notice you have some C++ questions in your profile. If you understand the concept of multiple-inheritance from C++ (referring to classes that inherit characteristics from more than one other class), Java does not allow this, but it does have keyword interface, which is sort of like a pure virtual class in C++. As mentioned by lots of people, you extend a class (and you can only extend from one), and you implement an interface -- but your class can implement as many interfaces as you like.

    Ie, these keywords and the rules governing their use delineate the possibilities for multiple-inheritance in Java (you can only have one super class, but you can implement multiple interfaces).

    0 讨论(0)
提交回复
热议问题