InterviewSolution
| 1. |
A superclass Number is defined to calculate the factorial of a number. Define a subclass Series to find the sum of the series S = 1! + 2! + 3! + 4! + ………. + n!The details of the members of both classes are given below:Class name: Number Data member/instance variable:n: to store an integer numberMember functions/methods:Number(int nn): parameterized constructor to initialize the data member n=nnint factorial(int a): returns the factorial of a number(factorial of n = 1 × 2 × 3 × …… × n) void display() Class name: SeriesData member/instance variable:sum: to store the sum of the series Member functions/methods:Series(…) : parameterized constructor to initialize the data members of both the classesvoid calsum(): calculates the sum of the given seriesvoid display(): displays the data members of both the classesAssume that the superclass Number has been defined. Using the concept of inheritance, specify the class Series giving the details of the constructor(…), void calsum() and void display().The superclass, main function and algorithm need NOT be written. |
|
Answer» import java.io.*; import java.util. Scanner; class Number{ int n; public Number(int nn) { n = nn; } public int factorial(int a) { if(a <= 1) return 1; return a * factorial(--a); } public void display() { System.out.println(“Number: ” + n); } } class Series extends Number { int sum; public Series(int n) { super(n); sum = 0; } public void calcSum() { for(int i = 1; i <= n; i++) { sum += super.factorial(i); } } public void display() { super, display(); System.out.println(“Series sum: ” + sum); } } class Factorial { public static void main(String args[ ]) throws IOException { Scanner sc = new Scanner(System.in); System.out.print(“Enter the number: ”); int niun = sc.nextInt(); Series obj = new Series(num); obj.calcSum(); obj.display(); } } |
|