0% found this document useful (0 votes)
9 views23 pages

Chapter-8 Encapsulation & Inheritance

The document contains a series of Java programming exercises focused on concepts of encapsulation and inheritance. It includes multiple class definitions with specific data members and methods, such as Prime, Factorial, Salary, Matrix, Account, Sale, and Check, along with their implementations. Additionally, it addresses questions related to inheritance, access specifiers, and class relationships in Java.

Uploaded by

Devbrat Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views23 pages

Chapter-8 Encapsulation & Inheritance

The document contains a series of Java programming exercises focused on concepts of encapsulation and inheritance. It includes multiple class definitions with specific data members and methods, such as Prime, Factorial, Salary, Matrix, Account, Sale, and Check, along with their implementations. Additionally, it addresses questions related to inheritance, access specifiers, and class relationships in Java.

Uploaded by

Devbrat Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chapter-8 Encapsulation & Inheritance

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 [Link];

public class Prime

private int n;

public void input() {

Scanner in = new Scanner([Link]);

[Link]("Enter the number: ");

n = [Link]();

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)

[Link]("Prime Number");

else

[Link]("Not a Prime Number");

public static void main(String args[]) {

Prime obj = new Prime();

[Link]();

[Link]();

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 [Link];

public class Factorial

{
private int n;

public void input() {

Scanner in = new Scanner([Link]);

[Link]("Enter the number: ");

n = [Link]();

public void fact() {

int f = 1;

for (int i = 1; i <= n; i++)

f *= i;

[Link]("Factorial of " + n

+ " = " + f);

public static void main(String args[]) {

Factorial obj = new Factorial();

[Link]();

[Link]();

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 [Link];

public class Salary

private int basic;

public void input() {

Scanner in = new Scanner([Link]);

[Link]("Enter the basic pay: ");

basic = [Link]();

public void display() {

double da = basic * 0.3;

double hra = basic * 0.1;

double gross = basic + da + hra;

[Link]("da=" + da);

[Link]("hra=" + hra);

[Link]("gross=" + gross);

public static void main(String args[]) {

Salary obj = new Salary();

[Link]();

[Link]();

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 [Link];

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([Link]);

for (int i = 0; i < ARR_SIZE; i++) {

[Link]("Enter elements of row "

+ (i+1) + ":");

for (int j = 0; j < ARR_SIZE; j++) {

m[i][j] = [Link]();

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

[Link]("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];

[Link]("Column " + (i+1) + " sum: " + cSum);

public static void main(String args[]) {

Matrix obj = new Matrix();

[Link]();

[Link]();

[Link]();

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() {

[Link]("Account Number: " + acno);

[Link]("Balance: " + balance);

[Link]("Interest: " + si);

[Link]("Amount: " + amt);

}
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 [Link];

public class Sale

protected String title;

protected String author;

protected String publication;

protected double price;


public void input() {

Scanner in = new Scanner([Link]);

[Link]("Enter book title: ");

title = [Link]();

[Link]("Enter book author: ");

author = [Link]();

[Link]("Enter publication name: ");

publication = [Link]();

[Link]("Enter book price: ");

price = [Link]();

public void display() {

[Link]("Book Title: " + title);

[Link]("Book Author: " + author);

[Link]("Publication: " + publication);

[Link]("Price: " + price);

import [Link];

public class Purchase extends Sale

private int noc;

private double amount;

public void accept() {

Scanner in = new Scanner([Link]);

[Link]("Enter no. of copies purchased: ");

noc = [Link]();
}

public void calculate() {

amount = noc * price;

public void show() {

display();

[Link]("No. of copies: " + noc);

[Link]("Amount: " + amount);

public static void main(String args[]) {

Purchase obj = new Purchase();

[Link]();

[Link]();

[Link]();

[Link]();

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 [Link];

public class Number

protected int n;

public void input() {

Scanner in = new Scanner([Link]);

[Link]("Enter the number: ");

n = [Link]();

public void display() {

[Link]("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;

[Link]("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)

[Link](n + " is Palindrome number");

else

[Link](n + " is not Palindrome number");

public static void main(String args[]) {

Check obj = new Check();

[Link]();

[Link]();

[Link]();

}
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 Class

 It is the existing class from which new classes are derived.

 It cannot use the data members and member methods of the target class.

 It is also known as base class or parent class.

Target

 It is the class that inherits the data members and member methods from the Super Class.

 It can use the inherited data members and member methods of the Super 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;

[Link]("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() {

[Link]("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 [Link]. 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() {

[Link]("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

*/
[Link]("x = " + x);

/*

* y is accessible as it is protected

*/

[Link]("y = " + y);

/*

* This will give ERROR!!!

* z is not accessible as it is private

*/

[Link]("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() {

[Link](name);

class StaticExampleTest {

public static void main(String[] args) {

StaticExample obj1 = new StaticExample("Red");

StaticExample obj2 = new StaticExample("Blue");

StaticExample obj3 = new StaticExample("Green");

[Link]("Total objects of StaticExample class = " + [Link]);

Output of this program is:

Total objects of StaticExample class = 3

You might also like