Interfaces vs Abstract Classes

1. in interfaces you cannot define a body of a method, whereas it’s optional in abstract classes;

public interface Animal{
	public void eat();
	public String getTypeOfAnimal(final String type);
}

public abstract class Animal{
	abstract void eat();
	String getTypeOfAnimal(final String type){
		System.out.println("Given type of the animal is: " + type);
	}
}

2.Defined variables in an interface have to be constants, once you fix the value you cannot alter it, whereas you are able to fix variables as constants or non constants in an abstract class

public interface SystemProperties{
public static final int CPU_CORE_COUNT = 4;
public static final String OS_NAME = "unix";

public abstract class SystemProperties {

	public static final int CPU_CORE_COUNT = 4;
	public String OS_NAME;
	
	public SystemProperties(final String OS_NAME) {
		this.OS_NAME = OS_NAME;
	}
}

3. In interfaces constructors do not exist, you don’t have to initialize a base interface’s constructor, neither do you have to pass variables defined in there, but in abstract classes all the extending concrete derived classes are obligated to call the base class’s constructor

public abstract class Animal {

	protected String food;
	protected double avgLife;
	
	public Animal(String food, double avgLife) {
		this.food = food;
		this.avgLife = avgLife;
	}
}

public class Lion extends Animal {

	public Lion(String food, double avgLife) {
			super(food, avgLife);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *