Skip to content

Object Oriented Programming in java

Declare an interface called “MyFirstInterface”. Declare integer type variable called “x”. Declare an abstract method called “display()”.


  1. Try to declare the variable with/without public, static and final keywords. Is there any difference between these two approaches? Why?
  2. Declare the abstract method with/without abstract keyword. Is there any difference between these two approaches? Why?
  3. Implement this into a class called “IntefaceImplemented” . Override all the abstract methods. Try to change the value of x inside this method and print the value of x. Is it possible for you to change x? why?

Best Answer

  • How to declare an interface in Java?

    An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

    Syntax:

      interface <MyFirstInterface>{        
        // declare constant fields  
        // declare methods that abstract  
        // by default.  
      }  
    


    Abstract method in interface

    All the methods of an interface are public abstract by default. You cannot have concrete (regular methods with body) methods in an interface.

    //Interface
    interface Multiply{
       //abstract methods
       public abstract int multiplyTwo(int n1, int n2);
       
       /* We need not to mention public and abstract in interface
        * as all the methods in interface are 
        * public and abstract by default so the compiler will
        * treat this as 
        * public abstract multiplyThree(int n1, int n2, int n3);
        */
       int multiplyThree(int n1, int n2, int n3);
    
       /* Regular (or concrete) methods are not allowed in an interface
        * so if I uncomment this method, you will get compilation error
        * public void disp(){
        *    System.out.println("I will give error if u uncomment me");
        * }
        */
    }
    
    class Demo implements Multiply{
       public int multiplyTwo(int num1, int num2){
          return num1*num2;
       }
       public int multiplyThree(int num1, int num2, int num3){
          return num1*num2*num3;
       }
       public static void main(String args[]){
          Multiply obj = new Demo();
          System.out.println(obj.multiplyTwo(3, 7));
          System.out.println(obj.multiplyThree(1, 9, 0));
       }
    }
    

    Output:

    21
    0
    


Sign In or Register to comment.