Chapter - 8 APC

 

Chapter 8

Encapsulation and Inheritance

Class 10 - APC Understanding Computer Applications with BlueJ


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

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

Answer the following

Question 1

What is meant by base class?

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

Question 2

Differentiate between super class and target.

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 3

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.

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);
    }
}

Question 4

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

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. Example:

class A {
    protected int amount;
}

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

Question 5

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.

All the data members and member functions of a class are accessible from the member function of the same class.

(b) in the member function of another class.

This other class should be a subclass of the given class then the public and protected data members and member functions will be accessible in this other class.

(c) in the member function of base class.

Base class doesn't have access to the data members and member functions of the derived class.

Question 6

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

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 7

Give reasons:

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

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) In what circumstances is a class derived privately?

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

Question 8

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

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 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 9

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.

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.

Below 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 10

Why is the main method in Java so special?

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 11

What is encapsulation?

The process of wrapping or grouping of data and functions in such a way that they are used as a single unit is known as encapsulation.

Question 12

In what way does a class enforce data hiding?

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 13

What are the types of visibility modes used in Java?

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 14

What will happen if data members are declared private.

Data members declared as private are accessible only inside their own class where they are declared and nowhere else.

Question 15

Can a private member be accessed by

(a) a member of the same class?
Yes

(b) a member of other class?
No

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

Question 16

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

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 17

What is meant by a static data member? Show its application with the help of an example

The data members of a class that are declared using the keyword static are called static data members. All objects of a class share the same copy of static data members. They are usually accessed using the class name instead of an object. Below example shows the use of static data member count to keep the track of the total number of objects created for the class:

class StaticExample {
    static int count;
    private String name;

    public StaticExample(String n) {
        name = n;
        count++;
    }

    public void showName() {
        System.out.println(name);
    }
}

class StaticExampleTest {
    public static void main(String[] args) {
        StaticExample obj1 = new StaticExample("Red");
        StaticExample obj2 = new StaticExample("Blue");
        StaticExample obj3 = new StaticExample("Green");
        System.out.println("Total objects of StaticExample class = " + StaticExample.count);
    }
}

Output of this program is:

Total objects of StaticExample class = 3

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 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);
    }
}
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();
    }
}
Output
BlueJ output of Sale.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.]

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

Second largest number in java using ternary operator

 //Largest second number using ternary operator public class Main { public static void main(String[] args) { int a=5,b=6,c=7; int ...