0% found this document useful (0 votes)
5 views

Exp 2.3 Java

Uploaded by

aslantargaryen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Exp 2.3 Java

Uploaded by

aslantargaryen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment:.2.3

Student Name:SACHIN KUMAR SACHAN UID:21BCS9802


Branch: CSE Section/Group: 905/A
rd
Semester: 3 Date of Performance:27/10/2022
Subject Name: OBJECT ORIENTED Subject Code:21CSH-218
PROGRAMMING USING JAVA

Aim of the practical:

Hackerrank problem related to interface.

Objective:

A Java interface can only contain method signatures and fields. The interface can be used to

achieve polymorphism. In this problem, you will practice your knowledge on interfaces.

You are given an interface AdvancedArithmetic which contains a method signature int

divisor_sum(int n). You need to write a class called MyCalculator which implements the

interface.

divisorSum function just takes an integer as input and return the sum of all its divisors. For

example divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12. The value of n will

be at most 1000.

Read the partially completed code in the editor and complete it. You just need to write the

MyCalculator class only. Your class shouldn't be public.


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

ProgramCode:

import java.util.*;
interface AdvancedArithmetic{
int divisor_sum(intn);
}

class MyCalculator implements AdvancedArithmetic


{
public int divisor_sum(int n)
{
if (n <= 1)
{
return n;
}
int res = n + 1;
for (int i = 2; i< n; i++) {
if (n % i == 0) {
res += i;
}
}
return res;
}
}
class Solution{
public static void main(String []args){
MyCalculatormy_calculator = new MyCalculator();
System.out.print("I implemented: ");
ImplementedInterfaceNames(my_calculator);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(my_calculator.divisor_sum(n) + "\n");
sc.close();
}
/*
* ImplementedInterfaceNames method takes an object and prints the name of the
interface s it implemented
*/
static void ImplementedInterfaceNames(Object o){
Class[] theInterfaces = o.getClass().getInterfaces();
for (int i = 0; i<theInterfaces.length; i++){
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

String interfaceName = theInterfaces[i].getName();


System.out.println(interfaceName);
}
}}

Output:

Learning outcomes (What I have learnt):


1. I have learnt how to achieve polymorphism in java using interface.

2. I have learnt how to write an interface.

3. I have learnt how to write a class which implements the interface.

You might also like