# Java Abstract Class V.S Java Interface ###### tags: `Java` `Abstract Class` `Interface` [TOC] ## Abstract Class ### What is Abstract Class? It is a class we cannot instantiate, however we can extend from it. This means we can inherit all the variables and also override its methods. >++**Note:**++ >A class can only extend **ONE** abstract class. [color=#2bc48e] ### When do we use it? I would use it when ____ **IS** ____. ***What do you mean?*** Let say you have many classes such as Bunny, Elephant, Dog and Cat. They all share many attributes and actions, because they are animals, therefore, we might make an abstract class with similar attributes and methods which can be overwritten. ### Abstract Class Example ```java== //abstract parent class abstract class Animal{ public abstract void sound(); public abstract void eat(); void state(){ System.out.println("Animal!"); } } //class extending from an abstract class public class Dog extends Animal{ public void sound(){ System.out.println("Woof"); } public void eat(){ System.out.println("Dog is eating."); } } public static void main(String args[]){ Animal obj = new Dog(); obj.sound(); } ``` ## Interface ### What is Interface? An interface is always public and its methods must always be overwritten. Class can implement **multiple** interfaces. >++**Note:**++ >1. We can not instantiate an interface but we can instantiate a class that implements it. >2. Interface can only have abstract methods.[color=red] ### When to use Interface? I would use it when different things share the same functions or actions, but they are not the same thing. For example: A folder and USB, both can do the action of **"SAVING"** but they are not even from same category. ### Interface Example ```java== public interface saveInterface{ void save(); } public class USB implements saveInterface{ @Override public void save(){ } } ```