Java find output programs (Interface) | set 3

Find the output of Java programs | Interface | Set 3: Enhance the knowledge of Java Interface concepts by solving and finding the output of some Java programs.
Submitted by Nidhi, on February 03, 2021

Question 1:

interface ICalc {
  abstract void Addition(int num1, int num2);
  static void Subtraction(int num1, int num2) {
    int sub = 0;

    sub = num1 - num2;
    System.out.println("Subtraction: " + sub);
  }
}

class Calc implements ICalc {
  public void Addition(int num1, int num2) {
    int sum = 0;

    sum = num1 + num2;
    System.out.println("Addition: " + sum);
  }
}

public class InfEx {
  public static void main(String[] args) {
    Calc C = new Calc();
    C.Addition(40, 60);

    ICalc.Subtraction(60, 40);
  }
}

Output:

Addition: 100
Subtraction: 20

Explanation:

In the above program, we created an interface ICalc that contains a declaration of abstract method Addition() and we defined static method Subtraction(). Then we implemented Addition() into Calc class.

Now look to the main() method of InfEx class - Here, we created object C of Calc class. Then we called the Addition() method using object C and then we called Subtraction() using the ICalc interface.

Question 2:

interface ICalc {
  abstract void Addition(int num1, int num2);
  static void Subtraction(int num1, int num2) {
    int sub = 0;

    sub = num1 - num2;
    System.out.println("Subtraction: " + sub);
  }
}

class Calc implements ICalc {
  public void Addition(int num1, int num2) {
    int sum = 0;

    sum = num1 + num2;
    System.out.println("Addition: " + sum);
  }
}

public class InfEx {
  public static void main(String[] args) {
    Calc * C = new Calc();
    C ->Addition(40, 60);

    ICalc.Subtraction(60, 40);
  }
}

Output:

/InfEx.java:23: error: not a statement
    C ->Addition(40, 60);
    ^
1 error

Explanation:

The above program will generate a syntax error because of the below statements,

InfEx.java:29: error: not a statement
        C->Addition(40,60);
        ^
1 error

In the above statements, we created pointer, but java does not support pointers.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.