can an abstract class have implemented methods code example
Example 1: when we should use abstract class
When to use an abstract class
An abstract class is a good choice if we are using the inheritance concept since it provides a common base class implementation to derived classes.
An abstract class is also good if we want to declare non-public members. In an interface, all methods must be public.
If we want to add new methods in the future, then an abstract class is a better choice. Because if we add new methods to an interface, then all of the classes that already implemented that interface will have to be changed to implement the new methods.
If we want to create multiple versions of our component, create an abstract class. Abstract classes provide a simple and easy way to version our components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, we must create a whole new interface.
Abstract classes have the advantage of allowing better forward compatibility. Once clients use an interface, we cannot change it; if they use an abstract class, we can still add behavior without breaking the existing code.
If we want to provide common, implemented functionality among all implementations of our component, use an abstract class. Abstract classes allow us to partially implement our class, whereas interfaces contain no implementation for any members.
Example 2: write a program in which an abstract class is being defined containg an abstract method omputer(int a, int b) and a non abstract method as well
abstract class Sum{
public abstract int compute(int a, int b);
public void disp(){
System.out.println("Method of class Sum");
}
}
class Demo extends Sum{
public int compute(int a, int b){
return a+b;
}
public static void main(String args[]){
Sum obj = new Demo();
System.out.println(obj.compute(3, 7));
obj.disp();
}
}