What is the difference between an interface and abstract class?

前端 未结 30 1820
情歌与酒
情歌与酒 2020-11-21 11:51

What exactly is the difference between an interface and abstract class?

30条回答
  •  难免孤独
    2020-11-21 12:10

    If you have some common methods that can be used by multiple classes go for abstract classes. Else if you want the classes to follow some definite blueprint go for interfaces.

    Following examples demonstrate this.

    Abstract class in Java:

    abstract class animals
    {
        // They all love to eat. So let's implement them for everybody
        void eat()
        {
            System.out.println("Eating...");
        }
        // The make different sounds. They will provide their own implementation.
        abstract void sound();
    }
    
    class dog extends animals
    {
        void sound()
        {
            System.out.println("Woof Woof");
        }
    }
    
    class cat extends animals
    {
        void sound()
        {
            System.out.println("Meoww");
        }
    }
    

    Following is an implementation of interface in Java:

    interface Shape
    {
        void display();
        double area();
    }
    
    class Rectangle implements Shape 
    {
        int length, width;
        Rectangle(int length, int width)
        {
            this.length = length;
            this.width = width;
        }
        @Override
        public void display() 
        {
            System.out.println("****\n* *\n* *\n****"); 
        }
        @Override
        public double area() 
        {
            return (double)(length*width);
        }
    } 
    
    class Circle implements Shape 
    {
        double pi = 3.14;
        int radius;
        Circle(int radius)
        {
            this.radius = radius;
        }
        @Override
        public void display() 
        {
            System.out.println("O"); // :P
        }
        @Override
        public double area() 
        { 
            return (double)((pi*radius*radius)/2);
        }
    }
    

    Some Important Key points in a nutshell:

    1. The variables declared in Java interface are by default final. Abstract classes can have non-final variables.

    2. The variables declared in Java interface are by default static. Abstract classes can have non-static variables.

    3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..

提交回复
热议问题