Computer Applications

Write a program to define class with the following specifications:

Class name — Number

Data members/ Instance variables:

  1. int n — to hold an integer number

Member methods:

  1. void input() — to accept an integer number in n
  2. void display() — to display the integer number input in n

Now, inherit class Number to another class Check that is defined with the following specifications:

Class name — Check

Data members/ Instance variables:

  1. int fact
  2. int revnum

Member methods:

  1. void find() — to find and print factorial of the number used in base class
  2. void palindrome() — to check and print whether the number used in base class is a palindrome number or not

[A number is said to be palindrome if it appears the same after reversing its digits. e.g., 414, 333, 515, etc.]

Java

Encapsulation & Inheritance in Java

30 Likes

Answer

import java.util.Scanner;

public class Number
{
    protected int n;
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        n = in.nextInt();
    }
    
    public void display() {
        System.out.print("Number = " + n);
    }
}
public class Check extends Number
{
    private int fact;
    private int revnum;
    
    public void find() {
        fact = 1;
        for (int i = 2; i <= n; i++)
            fact *= i;
        System.out.println("Factorial of " + n + " = " + fact);
    }
    
    public void palindrome() {
        revnum = 0;
        int t = n;
        while (t != 0) {
            int digit = t % 10;
            revnum = revnum * 10 + digit;
            t /= 10;
        }
        
        if (n == revnum)
            System.out.println(n + " is Palindrome number");
        else
            System.out.println(n + " is not Palindrome number");
    }
    
    public static void main(String args[]) {
        Check obj = new Check();
        obj.input();
        obj.find();
        obj.palindrome();
    }
}

Variable Description Table

Program Explanation

Output

Answered By

13 Likes


Related Questions