KnowledgeBoat Logo
OPEN IN APP

Chapter 8

Encapsulation and Inheritance

Class 10 - APC Understanding Computer Applications with BlueJ



Multiple Choice Questions

Question 1

Which type of data is not accessed in a derived class?

  1. Public
  2. Private
  3. Protected
  4. None

Answer

Private

Reason — Private data members and member methods cannot be accessed in a derived class.

Question 2

A private member method is only accessed:

  1. In the scope of the same class in which it is defined.
  2. Anywhere outside the class in which it is defined.
  3. In the derived class.
  4. None of the above.

Answer

In the scope of the same class in which it is defined.

Reason — A private member method is only accessed in the scope of the same class in which it is defined.

Question 3

A ............... variable is a common field for all the objects of a class.

  1. local variable
  2. global variable
  3. class variable
  4. instance variable

Answer

class variable

Reason — A class variable is a common field for all the objects of a class.

Question 4

Which of the following data is a separate field for all the objects of a class?

  1. Local variable
  2. Class variable
  3. Instance variable
  4. Primitive variable

Answer

Instance variable

Reason — Instance variable is a separate field for all the objects of a class.

Question 5

Which of the following is a combination of more than one inheritance system?

  1. Hybrid inheritance
  2. Multiple inheritance
  3. Single inheritance
  4. Hierarchical inheritance

Answer

Hybrid inheritance

Reason — Hybrid inheritance is a combination of more than one inheritance system.

Question 6

What is another name of multilevel inheritance?

  1. Single inheritance
  2. Nested inheritance
  3. Multiple inheritance
  4. Derived inheritance

Answer

Nested inheritance

Reason — Nested inheritance is another name of multilevel inheritance.

Fill in the blanks

Question 1

Derived class inherits from base class.

Question 2

Because of Inheritance the reusability of an object code comes into existence.

Question 3

Super class is the term used for base class.

Question 4

A sub/target/derived class derives a base class.

Question 5

A sub/derived class is also known as Target.

Question 6

The process of sharing characteristics with classes is called Inheritance.

Question 7

A derived class inherits from a single base is known as Single inheritance.

Question 8

Java doesn't allow multiple inheritance.

Question 9

A base class derived by a target, in turn used as base class for another target is called multilevel or nested inheritance.

State True or False

Question 1

Inheritance supports reusability.
True

Question 2

During inheritance, the public and protected members remain in the same form in the derived class.
False

Question 3

Inheritance is a transitive property.
True

Question 4

Base class is used to inherit the property of a derived class.
False

Question 5

During inheritance if no visibility mode is declared then the system automatically assumes it to be private.
False

Question 6

Visibility modes decide the access provided to the members from the target.
False

Question 7

Constructors of base and derived classes are automatically invoked while creating the objects of derived class.
True

Question 8

A target does not have access to the private members of base class.
True

Question 9

A single target inheriting many bases is known as multilevel inheritance.
False

Case-Study based question

Question 1

A number is said to be Armstrong if the sum of cube of its digits is equal to the same number.
For example,
153 = 13 + 53 + 33
Hence, 153 is an Armstrong number.

A program using a class is designed below to check and display whether a number 'num' is an Armstrong number or not. There are some places in the program left blank marked with ?1?, ?2?, ?3? and ?4? to be filled with suitable condition/expression.

class Armstrong { 
    private int num; 
    Armstrong(int n) {
         num = n; 
    boolean check( ) { 
        int nm = num; 
        while(...?1?...) {
            digit = nm % 10; 
            sum = sum + ...?2?... ;
            nm =  ...?3?... ;  
        }
        if (sum == num) 
            return(true); 
        else 
            return(false); 
    } 
    void display( ) {
        boolean ch = check( ); 
        if(ch == ...?4?... ) 
            System.out.println("Number is Armstrong"); 
        else 
            System.out.println("Number is not Armstrong"); 
    }
    }
 }

Based on the above discussion, answer the following questions:

(a) What will be filled in place of ?1?

(b) What will be filled in place of ?2?

(c) What will be filled in place of ?3?

(d) What will be filled in place of ?4?

Answer

(a) nm > 0

(b) Math.pow(digit,3)

(c) nm / 10

(d) true

The complete program is as follows:

class Armstrong { 
    private int num; 
    Armstrong(int n) {
         num = n; 
    boolean check( ) { 
        int nm = num; 
        while(nm > 0) {
            digit = nm % 10; 
            sum = sum + Math.pow(digit , 3);
            nm = nm / 10 ;  
        }
        if (sum == num) 
            return(true); 
        else 
            return(false); 
    } 
    void display( ) {
        boolean ch = check( ); 
        if(ch == true ) 
            System.out.println("Number is Armstrong"); 
        else 
            System.out.println("Number is not Armstrong"); 
    }
    }
 }

Answer the following

Question 1

What is encapsulation?

Answer

Encapsulation is the process of wrapping data and functions together as a unit called class.

Question 2

In what way does a class enforce data hiding?

Answer

A class enforces data hiding through access specifiers. Java provides three access specifiers for its class members — public, private and protected. The private members of a class are only accessible within the class. They are hidden to the code outside the class. The protected members are accessible from classes within the same package and subclasses.

Question 3

What are the types of visibility modes used in Java?

Answer

Visibility modes used in Java are:

  1. private — private members are accessible only inside their own class.
  2. protected — protected members are accessible inside their own class, classes within the package and subclasses.
  3. public — public members are accessible in all the classes.

Question 4

What will happen if data members are declared private?

Answer

Data members declared as private are accessible only inside their own class where they are declared and nowhere else. They cannot be accessed in the derived classes also.

Question 5

What do you understand by 'inheritance'?

Answer

Inheritance is a concept of object oriented programming in which some properties of a class are shared by another class or classes.

Question 6

What is meant by base class?

Answer

A base class is a class that is inherited by another class. It facilitates the creation of other classes that can reuse the code implicitly inherited from the base class.

Question 7

Differentiate between super class and target.

Answer

Super ClassTarget
It is the existing class from which new classes are derived.It is the class that inherits the data members and member methods from the Super Class.
It cannot use the data members and member methods of the target class.It can use the inherited data members and member methods of the Super Class.
It is also known as base class or parent class.It is also known as derived class or sub class.

Question 8

What is the significance of using protected declaration during inheritance? Show with the help of an example.

Answer

A class member declared as protected can be accessed directly by all the classes within the same package and the subclasses of its class even if the subclasses are in different packages. For example:

class A {
    protected int amount;
}

class B extends A {
    public void displayAmount() {
        System.out.println("Amount = " + amount);
    }
}

Question 9

Main class by default inherits another class. Explain the given statement.

Answer

In Java, Object class is known as the base class for all the classes. This class is present in the default package of java which is java.lang. For this reason, we don’t need to inherit this class explicitly. But each and every class in Java inherits Object class implicitly.

Question 10

With the help of an example explain how you can access a private member of a base class.

Answer

Private member of a base class can be accessed through a public method of the base class which returns the private member. This is illustrated in the example given below:

class A {
    private int x;

    public A() {
        x = 10;
    }

    public int getX() {
        return x;
    }
}

class B extends A {
    public void showX() {
        System.out.println("Value of x = " + getX());
    }
}

Question 11

Why is the main method in Java so special?

Answer

Execution of the Java program begins with the main method. It is the main entry point to the program. It is called by Java Virtual Machine (JVM) to start the execution of the program.

Question 12

What is meant by scope of variables? Show its application with the help of an example.

Answer

Scope of variables refers to the extent of their usage in a program. Basically, a variable is used within the block in which it is declared. Based on the scope of usage, the variables can be categorised into three types:

  1. Instance Variables — The member variables that store the state of an object are known as instance variables.
  2. Class Variables (static variable) — A variable declared in a class with the static modifier is called a class variable.
  3. Local Variables — The variables declared inside a method or block are called local variables. The scope of local variables is limited to the method or the block they are declared in.

Consider the example given below:

class Scope {
    String name;
    static int companyname;
    double sal, extra; 
    Scope(String n, double x, double y) {
        companyname = "HCL";
        name = n;
        sal = x;
        extra = y;
    }
    void calculate()  {
        double total = sal + extra;
    }
    void disp() {
        System.out.println(name + " " + companyname);
        System.out.println("Salary = " + total);
    }
}

Let the objects of class Scope be created as:
Scope ob1 = new Scope("Amit Kumar", 30000.0 , 3500.0);
Scope ob2 = new Scope("Suraj Jain", 25000.0 , 2000);

Here, name, sal and extra are instance variables which will be accessible throughout the class and have different values for different objects.
Variable companyname is class variable and has the same value for each object of the class.
Variable total is a local variable of calculate(). It can be used only within the function and will generate an error — "Variable not found" when we try to access it in disp().

Question 13

In what way does the access specifier of the base class have access control over the derived class? Show with the help of an example.

Answer

Access specifier of the base class have access control over the derived class in the following way:

  1. Private members of base class cannot be accessed in the derived class.
  2. Public members of base class can be accessed as public members in the derived class.
  3. Protected members of base class can be accessed in the derived class and can be inherited by further sub classes.

The given example illustrates this:

class A {
    public int x;
    protected int y;
    private int z;

    public A() {
        x = 10;
        y = 20;
        z = 30;
    }

    public int sum() {
        return x + y + z;
    }
}

class B extends A {
    int total;

    void computeTotal() {
        /*
         * Public method sum() of base class
         * is accessible here
         */
        total = sum();
    }

    void display() {
        /*
         * x is accessible as it is public
         */
        System.out.println("x = " + x);

        /*
         * y is accessible as it is protected
         */
        System.out.println("y = " + y);

        /*
         * This will give ERROR!!!
         * z is not accessible as it is private
         */
        System.out.println("z = " + z);
    }
}

Question 14

Suppose, 'Happening' and 'Accident' are two classes. What will happen when Happening class derives from Accident class by using private visibility?

Answer

Java only supports public inheritance. If 'Happening' class derives from 'Accident' class in Java, then 'Happening' class will inherit all the public and protected data members and member methods of 'Accident' class.

Public members of 'Accident' class will behave as public members of 'Happening' class and protected members of 'Accident' class will behave as protected members of 'Happening' class.

Private members of 'Accident' class will not be accessible in 'Happening' class.

Question 15

Give reasons:

(a) In what circumstances is a class derived publicly?

(b) In what circumstances is a class derived privately?

Answer

(a) In Java, a base class can be derived by a subclass by using only public mode of inheritance. When a class is derived publicly, the public and protected members of the base class are accessible to the derived class. Private members of the base class are not inherited by derived class.

(b) Java doesn't support private and protected modes of Inheritance. Classes are always derived publicly in Java.

Question 16

Describe the methods of accessing the data members and member functions of a class in the following cases:

(a) in the member function of the same class.

(b) in the member function of another class.

(c) in the member function of base class.

Answer

(a) In the member function of the same class, all the data members and member functions of a class are accessible.

(b) In the member function of another class, the public and protected data members and member functions will be accessible if the other class is a subclass of the main class.

(c) In the member function of base class, data members and member functions of the derived class are not accessible.

Question 17

Can a private member be accessed by

(a) a member of the same class?

(b) a member of other class?

(c) a function which is not a member function?

Answer

(a) Yes

(b) No

(c) No

Question 18

Show with the help of an example how the following base classes can be derived in class bill to fulfill the given requirement:

class elect
{
    String n;
    float units;
    public void setvalue()
    {
        n = "SOURABH";
        units = 6879;

    }
}

Class bill uses data members charge and a member function to calculate the bill at the rate of 3.25 per unit and displays the charge. Class elect is inherited by class bill by using private visibility.

Answer

Class elect can be derived in class bill as shown below:

class bill extends elect {
    private double charge;
    public void calc() {
        charge = 3.25 * units;
        System.out.println("Charge = " + charge);
    }
}

Solutions to Unsolved Java Programs

Question 1

Write a program by using a class with the following specifications:

Class name — Prime

Data members — private int n

Member functions:

  1. void input() — to input a number
  2. void checkprime() — to check and display whether the number is prime or not

Use a main function to create an object and call member methods of the class.

import java.util.Scanner;

public class Prime
{
    private int n;
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        n = in.nextInt();
    }
    
    public void checkprime() {
        boolean isPrime = true;
        if (n == 0 || n == 1)
            isPrime = false;
        else {
            
            for (int i = 2; i <= n / 2; i++) {
                if (n % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }
        
        if (isPrime)
            System.out.println("Prime Number");
        else
            System.out.println("Not a Prime Number");
    }
    
    public static void main(String args[]) {
        Prime obj = new Prime();
        obj.input();
        obj.checkprime();
    }
}
Output
BlueJ output of Prime.java

Question 2

Write a program by using a class with the following specifications:

Class name — Factorial

Data members — private int n

Member functions:

  1. void input() — to input a number
  2. void fact() — to find and print the factorial of the number

Use a main function to create an object and call member methods of the class.

import java.util.Scanner;

public class Factorial
{
    private int n;
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        n = in.nextInt();
    }
    
    public void fact() {
        int f = 1;
        for (int i = 1; i <= n; i++)
            f *= i;
        System.out.println("Factorial of " + n 
            + " = " + f);
    }
    
    public static void main(String args[]) {
        Factorial obj = new Factorial();
        obj.input();
        obj.fact();
    }
}
Output
BlueJ output of Factorial.java

Question 3

Write a program by using a class with the following specifications:

Class name — Salary

Data members — private int basic

Member functions:

  1. void input() — to input basic pay
  2. void display() — to find and print the following:
    da = 30% of basic
    hra = 10% of basic
    gross = basic + da + hra

Use a main function to create an object and call member methods of the class.

import java.util.Scanner;

public class Salary
{
    private int basic;
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the basic pay: ");
        basic = in.nextInt();
    }
    
    public void display() {
        double da = basic * 0.3;
        double hra = basic * 0.1;
        double gross = basic + da + hra;
        System.out.println("da=" + da);
        System.out.println("hra=" + hra);
        System.out.println("gross=" + gross);
    }
    
    public static void main(String args[]) {
        Salary obj = new Salary();
        obj.input();
        obj.display();
    }
}
Output
BlueJ output of Salary.java

Question 4

Write a class program with the following specifications:

Class name — Matrix

Data members — int array m[][] with 3 rows and 3 columns

Member functions:

  1. void getdata() — to accept the numbers in the array
  2. void rowsum() — to find and print the sum of the numbers of each row
  3. void colsum() — to find and print the sum of numbers of each column

Use a main function to create an object and call member methods of the class.

import java.util.Scanner;

public class Matrix
{
    private final int ARR_SIZE = 3;
    private int[][] m;
    
    public Matrix() {
         m = new int[ARR_SIZE][ARR_SIZE];
    }
    
    public void getdata() {
        Scanner in = new Scanner(System.in);
        for (int i = 0; i < ARR_SIZE; i++) {
            System.out.println("Enter elements of row " 
                + (i+1) + ":");
            for (int j = 0; j < ARR_SIZE; j++) {
                m[i][j] = in.nextInt();
            }
        }
    }
    
    public void rowsum() {
        for (int i = 0; i < ARR_SIZE; i++) {
            int rSum = 0;
            for (int j = 0; j < ARR_SIZE; j++) {
                rSum += m[i][j];
            }
            System.out.println("Row " + (i+1) + " sum: " + rSum);
        }
    }
    
    public void colsum() {
        for (int i = 0; i < ARR_SIZE; i++) {
            int cSum = 0;
            for (int j = 0; j < ARR_SIZE; j++) {
                cSum += m[j][i];
            }
            System.out.println("Column " + (i+1) + " sum: " + cSum);
        }
    }
    
    public static void main(String args[]) {
        Matrix obj = new Matrix();
        obj.getdata();
        obj.rowsum();
        obj.colsum();
    }
}
Output
BlueJ output of Matrix.java

Question 5

Write a program to use a class Account with the following specifications:

Class name — Account

Data members — int acno, float balance

Member Methods:

  1. Account (int a, int b) — to initialize acno = a, balance = b
  2. void withdraw(int w) — to maintain the balance with withdrawal (balance - w)
  3. void deposit(int d) — to maintain the balance with the deposit (balance + d)

Use another class Calculate which inherits from class Account with the following specifications:

Data members — int r,t ; float si,amt;

Member Methods:

  1. void accept(int x, int y) — to initialize r=x,t=y,amt=0
  2. void compute() — to find simple interest and amount
    si = (balance * r * t) / 100;
    a = a + si;
  3. void display() — to print account number, balance, interest and amount

main() function need not to be used

public class Account
{
    protected int acno;
    protected float balance;
    
    public Account(int a, int b) {
        acno = a;
        balance = b;
    }
    
    public void withdraw(int w) {
        balance -= w;
    }
    
    public void deposit(int d) {
        balance += d;
    }
}
public class Calculate extends Account
{
    private int r;
    private int t;
    private float si;
    private float amt;
    
    public Calculate(int a, int b) {
        super(a, b);
    }
    
    public void accept(int x, int y) {
        r = x;
        t = y;
        amt = 0;
    }
    
    public void compute() {
        si = (balance * r * t) / 100.0f;
        amt = si + balance;
    }
    
    public void display() {
        System.out.println("Account Number: " + acno);
        System.out.println("Balance: " + balance);
        System.out.println("Interest: " + si);
        System.out.println("Amount: " + amt);
    }
}
Output
BlueJ output of Account.java

Question 6

Write a program by using class with the following specifications:

Class name — Sale

Data members/ Instance variables:

  1. String title, author,publication
  2. double price

Member methods:

  1. void input() — to accept title, author name and publication name and price of a book
  2. void display() — to display title, author name and publication name and price of a book

Now, create another class 'Purchase' that inherits class 'Sale' having the following specifications:

Class name — Purchase

Data members/ Instance variables:

  1. int noc
  2. int amount;

Member methods:

  1. void accept() — to enter the number of copies purchased
  2. void calculate( ) — to find the amount by multiplying number of copies ordered and price (i.e., noc * price)
  3. void show() — to display the elements describes in base class along with the number of copies purchased and amount to be paid to the shopkeeper
import java.util.Scanner;

public class Purchase extends Sale
{
    private int noc;
    private double amount;
    
    public void accept() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter no. of copies purchased: ");
        noc = in.nextInt();
    }
    
    public void calculate() {
        amount = noc * price;
    }
    
    public void show() {
        display();
        System.out.println("No. of copies: " + noc);
        System.out.println("Amount: " + amount);
    }
    
    public static void main(String args[]) {
        Purchase obj = new Purchase();
        obj.input();
        obj.accept();
        obj.calculate();
        obj.show();
    }
}
import java.util.Scanner;

public class Sale
{
    protected String title;
    protected String author;
    protected String publication;
    protected double price;
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter book title: ");
        title = in.nextLine();
        System.out.print("Enter book author: ");
        author = in.nextLine();
        System.out.print("Enter publication name: ");
        publication = in.nextLine();
        System.out.print("Enter book price: ");
        price = in.nextDouble();
    }
    
    public void display() {
        System.out.println("Book Title: " + title);
        System.out.println("Book Author: " + author);
        System.out.println("Publication: " + publication);
        System.out.println("Price: " + price);
    }
}
Output
BlueJ output of Purchase.java

Question 7

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.]

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();
    }
}
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);
    }
}
Output
BlueJ output of Check.java
PrevNext