Encapsulation and Inheritance
Which type of data is not accessed in a derived class?
- Public
- Private
- Protected
- None
Answer
Private
Reason — Private data members and member methods cannot be accessed in a derived class.
A private member method is only accessed:
- In the scope of the same class in which it is defined.
- Anywhere outside the class in which it is defined.
- In the derived class.
- 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.
A ............... variable is a common field for all the objects of a class.
- local variable
- global variable
- class variable
- instance variable
Answer
class variable
Reason — A class variable is a common field for all the objects of a class.
Which of the following data is a separate field for all the objects of a class?
- Local variable
- Class variable
- Instance variable
- Primitive variable
Answer
Instance variable
Reason — Instance variable is a separate field for all the objects of a class.
Which of the following is a combination of more than one inheritance system?
- Hybrid inheritance
- Multiple inheritance
- Single inheritance
- Hierarchical inheritance
Answer
Hybrid inheritance
Reason — Hybrid inheritance is a combination of more than one inheritance system.
What is another name of multilevel inheritance?
- Single inheritance
- Nested inheritance
- Multiple inheritance
- Derived inheritance
Answer
Nested inheritance
Reason — Nested inheritance is another name of multilevel inheritance.
Derived class inherits from base class.
Because of Inheritance the reusability of an object code comes into existence.
Super class is the term used for base class.
A sub/target/derived class derives a base class.
A sub/derived class is also known as Target.
The process of sharing characteristics with classes is called Inheritance.
A derived class inherits from a single base is known as Single inheritance.
Java doesn't allow multiple inheritance.
A base class derived by a target, in turn used as base class for another target is called multilevel or nested inheritance.
Inheritance supports reusability.
True
During inheritance, the public and protected members remain in the same form in the derived class.
False
Inheritance is a transitive property.
True
Base class is used to inherit the property of a derived class.
False
During inheritance if no visibility mode is declared then the system automatically assumes it to be private.
False
Visibility modes decide the access provided to the members from the target.
False
Constructors of base and derived classes are automatically invoked while creating the objects of derived class.
True
A target does not have access to the private members of base class.
True
A single target inheriting many bases is known as multilevel inheritance.
False
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");
}
}
}
What is encapsulation?
Answer
Encapsulation is the process of wrapping data and functions together as a unit called class.
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.
What are the types of visibility modes used in Java?
Answer
Visibility modes used in Java are:
- private — private members are accessible only inside their own class.
- protected — protected members are accessible inside their own class, classes within the package and subclasses.
- public — public members are accessible in all the classes.
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.
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.
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.
Differentiate between super class and target.
Answer
Super Class | Target |
---|---|
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. |
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);
}
}
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.
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());
}
}
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.
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:
- Instance Variables — The member variables that store the state of an object are known as instance variables.
- Class Variables (static variable) — A variable declared in a class with the
static
modifier is called a class variable. - 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()
.
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:
- Private members of base class cannot be accessed in the derived class.
- Public members of base class can be accessed as public members in the derived class.
- 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);
}
}
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.
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.
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.
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
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);
}
}
Write a program by using a class with the following specifications:
Class name — Prime
Data members — private int n
Member functions:
- void input() — to input a number
- 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();
}
}
Write a program by using a class with the following specifications:
Class name — Factorial
Data members — private int n
Member functions:
- void input() — to input a number
- 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();
}
}
Write a program by using a class with the following specifications:
Class name — Salary
Data members — private int basic
Member functions:
- void input() — to input basic pay
- 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();
}
}
Write a class program with the following specifications:
Class name — Matrix
Data members — int array m[][] with 3 rows and 3 columns
Member functions:
- void getdata() — to accept the numbers in the array
- void rowsum() — to find and print the sum of the numbers of each row
- 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();
}
}
Write a program to use a class Account with the following specifications:
Class name — Account
Data members — int acno, float balance
Member Methods:
- Account (int a, int b) — to initialize acno = a, balance = b
- void withdraw(int w) — to maintain the balance with withdrawal (balance - w)
- 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:
- void accept(int x, int y) — to initialize r=x,t=y,amt=0
- void compute() — to find simple interest and amount
si = (balance * r * t) / 100;
a = a + si; - 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);
}
}
Write a program by using class with the following specifications:
Class name — Sale
Data members/ Instance variables:
- String title, author,publication
- double price
Member methods:
- void input() — to accept title, author name and publication name and price of a book
- 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:
- int noc
- int amount;
Member methods:
- void accept() — to enter the number of copies purchased
- void calculate( ) — to find the amount by multiplying number of copies ordered and price (i.e., noc * price)
- 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);
}
}
Write a program to define class with the following specifications:
Class name — Number
Data members/ Instance variables:
- int n — to hold an integer number
Member methods:
- void input() — to accept an integer number in n
- 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:
- int fact
- int revnum
Member methods:
- void find() — to find and print factorial of the number used in base class
- 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);
}
}