Abstraction and Interface

JavaJavaBeginner
Practice Now

Introduction

Abstraction and interface are two other significant concepts in Java. Abstract class and interface are very different although there are some common points. Start this lab and comprehend the concepts.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/abstraction("`Abstraction`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inheritance("`Inheritance`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/interface("`Interface`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-178542{{"`Abstraction and Interface`"}} java/inner_classes -.-> lab-178542{{"`Abstraction and Interface`"}} java/abstraction -.-> lab-178542{{"`Abstraction and Interface`"}} java/classes_objects -.-> lab-178542{{"`Abstraction and Interface`"}} java/class_methods -.-> lab-178542{{"`Abstraction and Interface`"}} java/inheritance -.-> lab-178542{{"`Abstraction and Interface`"}} java/interface -.-> lab-178542{{"`Abstraction and Interface`"}} java/modifiers -.-> lab-178542{{"`Abstraction and Interface`"}} java/oop -.-> lab-178542{{"`Abstraction and Interface`"}} java/identifier -.-> lab-178542{{"`Abstraction and Interface`"}} java/arrays -.-> lab-178542{{"`Abstraction and Interface`"}} java/comments -.-> lab-178542{{"`Abstraction and Interface`"}} java/data_types -.-> lab-178542{{"`Abstraction and Interface`"}} java/operators -.-> lab-178542{{"`Abstraction and Interface`"}} java/output -.-> lab-178542{{"`Abstraction and Interface`"}} java/strings -.-> lab-178542{{"`Abstraction and Interface`"}} java/variables -.-> lab-178542{{"`Abstraction and Interface`"}} java/string_methods -.-> lab-178542{{"`Abstraction and Interface`"}} java/system_methods -.-> lab-178542{{"`Abstraction and Interface`"}} end

Abstraction

Abstraction is aimed at modeling and maintaining organizational structure. It doesn't provide many details. Details are left for implementation classes to add. For example, when you consider the case of Animal, complex details such as what behaviors they can exhibit are hidden from the user. Therefore, every specific animal implements the details itself; we just need to invoke the method. In OOP, abstraction is a process of hiding the implementation details from the user. Only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it. In Java, abstraction is achieved using abstract classes and interfaces.

We use keyword abstract to declare an abstract class. Abstract classes may or may not contain abstract methods (methods only with declaration and without body). But, if a class has at least one abstract method, then the class must be declared abstract. If a class is declared abstract, it cannot be instantiated. To use an abstract class, you have to inherit it in another class and provide implementations to the abstract methods in it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. Another way to use an abstract class is to invoke its class methods (static methods).

Example:

Write the following code in the /home/labex/project/abstractTest.java file:

// abstract class
abstract class Animal{
    // abstract method
    public abstract void grow();
}

abstract class Bird extends Animal{
    /*
     * this class extends Animal,
     * but doesn't implement Animal's abstract method grow(),
     * so this class is also declared as abstract,
     * abstract class can't be instantiated.
    */

    // this class has a concrete method
    public void sing(){
        System.out.println("I'm singing a song...");
    }
}
class Dog extends Animal{
    // In this class, we must implement the abstract method, or the subclass must stay abstract.
    public void grow(){
        System.out.println("I'm dog, I grow up.");
    }
}
public class abstractTest{
    public static void main(String[] args){
        Dog dog = new Dog();
        dog.grow();
    }
}

Output:

Run the abstractTest.java file using the following commands:

javac /home/labex/project/abstractTest.java
java abstractTest

See the output:

I'm dog, I grow up.

Interface

Interface is a collection of abstract methods. It means all the methods in the interface are abstract. An interface does not contain any constructors. An interface cannot contain instance fields; only static and final fields can be there in interface. An interface is not extended by a class; it is only implemented by a class. An interface can extend multiple interfaces. A class can implement many interfaces.

Example:

Write the following code in the /home/labex/project/interfaceTest.java file:

// use keyword interface to create an interface.
interface myInterface1 {
    // Variables in interface are public, static and final by default.
    String NAME = "Interface";

    // methods are  abstract and public by default.
    public void method1();
}
interface myInterface2 {
    // we can explicitly define variable in interface as public, static and/or final, or just like that of myInterface1.
    public final String ID = "1001";

    public void method2();
}
// myInterface3 has method of myInterface2, it extends from myInterface2.
interface myInterface3 extends myInterface2{
    public void method3();
}
// class interfaceTest must implement all the three methods of upper interfaces.
public class interfaceTest implements myInterface1,myInterface3 {
     /*
     * this class has three methods from three interfaces
     * also gets the two interfaces' variables
     */
    // implement method1()
    public void method1(){
        System.out.println("implement method1.");
    }
     // implement method2()
    public void method2(){}
     // implement method3()
    public void method3(){}
    public static void main(String[] args){
        // test the methods
        interfaceTest test = new interfaceTest();
        test.method1();
        test.method2();
        test.method3();
        System.out.println("I have properties:" + interfaceTest.NAME +", " +interfaceTest.ID);
    }
}

Output:

Run the interfaceTest.java file using the following commands:

javac /home/labex/project/interfaceTest.java
java interfaceTest

See the output:

implement method1.
I have properties:Interface, 1001

Summary

Abstract class and interface can decouple classes and give us clearer design ideas. None of them can be instantiated directly. Abstract classes support only single inheritance while interfaces support multiple inheritance and a class can implement many interfaces. Both of them provide some features of polymorphism which is the topic of the next lab.

Other Java Tutorials you may like