What is the difference between Abstraction and Polymorphism

后端 未结 11 720
挽巷
挽巷 2021-01-30 07:09

I seem to not understand two OOP concepts very well. Could you explain what abstraction and polymorphism are, preferably with real examples and

11条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 07:51

    P.S: recently started learning java answer is based on my observation please correct me if i am wrong.

    Abstraction and Polymorphism basically deep down does almost same work in programming .

    let's Take a car for example..

    it doesn't matter whether it is a Ford mini-van, Ferrari exotic, Land-Rover SUV or a BMW sedan they all follow a basic design of a car i.e an engine, a steering wheel , a gear box , lights , indicators and list goes on . what makes them different is their specific implementations like Ferrari might have a more powerful engine than a mini van, a suv might have a different gear box hence A car (Superclass over here) has been implemented by subclasses (sedan, suv , mini-van, exotic) This is polymorphism, a basic idea being inherited or implemented by adding other specification. a 4 wheel vehicle (superclass) being implemented in various forms (subclasses)

    Now, Abstraction , by definition it means hiding the details and making user see what is required by him..

    Let's take example of car again.. You use gear but you don't know exactly the mechanism of how exactly the gear works and changes speed and all..

    Now over to coding Part.

    Abstract classes are incomplete classes and for a class to be abstract as the name suggest they need to have an incomplete method that needs to be completed by the subclass inheriting the superclass , IF they don't complete the abstract method they will stay incomplete as well.

    abstract class car {
      abstract void gear();
    }
    
    class sedan extends car {
     public void gear()
     {
      //complete the method
     }
    }
    

    also you can not create objects of abstract classes because class is not complete. Yet these abstract classes can have static methods , arguments , concrete methods BUT for them to be abstract they need one abstract method. So one basic abstract superclass is implemented in other subclasses where they complete it By looking at the method declaration we can estimate what exactly the method is doing, what it is going to return. But we don't know how exactly the abstract method will be implemented.

    By using abstract classes or interfaces , we can achieve abstraction in Java. As we all know that abstract classes, interfaces contains abstract methods

    We can only estimate how they will work . We get to know how they work, once we provided the method implementation in the classes which implement the corresponding abstract class or interface.

    HENCE, abstract basically helps polymorphism.

提交回复
热议问题