when to use abstract classes and interfaces in java code example

Example 1: abstract class example in java

//abstract parent class
abstract class Animal{
   //abstract method
   public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{

   public void sound(){
	System.out.println("Woof");
   }
   public static void main(String args[]){
	Animal obj = new Dog();
	obj.sound();
   }
}

Example 2: how to use an abstract class in java

interface methods{
    public void hey();
    public void bye();
}

//unable to implement all the abstract methods in the interface so 
// the other class automatically becomes abstract
abstract class other implements methods{
    public void hey(){
        System.out.println("Hey");
    }
}

//able to implement all the methods so is not abstract
class scratch implements methods {
    public void hey(){
        System.out.println("Hey");
    }
    public void bye() {
        System.out.println("Hey");
    }
}

Tags:

Java Example