+ 2

Where is the difference between abstract Class and interface?

Why need interface, where abstract class is present?

8th Dec 2019, 3:34 AM
Nazmul Islam Naim
Nazmul Islam Naim - avatar
2 Réponses
+ 6
Adding to Avinesh's answer... Abstract classes are great for sharing common implementation across sub types and interfaces are great for creating a contract for polymorphic behavior across any types. Declaring a class as abstract will restrict it to only be used as a base type (or super class). The compiler will not allow an abstract type to be instantiated as an object. This is in contrast to declaring a class as sealed, which prohibits the type from being extended by a sub class (or derived type). Abstract classes are useful as base types containing common methods and properties for derived types but is, itself, not sufficient enough to have meaning as an object instance. I tend to use abstract classes for common implementation of code in scenarios where it makes sense.
2nd Apr 2020, 11:08 PM
David Carroll
David Carroll - avatar
+ 4
1) Interface methods are by default abstract so the class implementing it must agree to the contract of providing implementation for all the methods of the interface. I'm not considering the default and static methods in interface. 2) Abstract classes can have an abstract method or it might not at all have an abstract method and can still be declared as an abstract class. But if there is an abstract method then it is compulsory to declare the class abstract. 3) Abstract class has constructor whereas an interface does not have one. 4) We use an interface if we want the implementing class to not have any common behaviours and each method has a different implementation. 5) We use an abstract class where the extending class object might have some common behaviour and few new ones that can be implemented. 6) A non-abstract class which gives implementation to all methods of either interface or abstract class is called a concrete class.
8th Dec 2019, 5:32 AM
Avinesh
Avinesh - avatar