Explain with example to describe when to use abstract class and interface?
Consider a scenario where all Cars will have 4 tyres and other features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a default implementation for tyres will be provided.
public abstract class Car { private final static TOTAL_TYRES=4; public abstract String getCarName(); public final int getNoOfTyres(){ return TOTAL_TYRES; } }
Consider a scenario where Cars can have any number of tyres and other features can also be different. In this case interface will be created.
public interface Car { public abstract String getCarName(); public abstract int getNoOfTyres(); }
Hello! I am Narayanaswamy founder and admin of narayanatutorial.com. I have been working in the IT industry for more than 12 years. NarayanaTutorial is my web technologies blog. My specialties are Java / J2EE, Spring, Hibernate, Struts, Webservices, PHP, Oracle, MySQL, SQLServer, Web Hosting, Website Development, and IAM(ForgeRock) Specialist
I am a self-learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.