0% found this document useful (0 votes)
22 views

Adobe Scan 15-Oct-2024

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

Adobe Scan 15-Oct-2024

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

SOLVED PROBLEMS ON ENCAPSULATION AND INHERITANCE

Write a program by using a class name Calculator with the following


Prog.
I specifications:
Calculator
Class name :
Data Members//Instance variables : private int result
Member Methods:
Calculator( ) : constructor to initialize result with zero
: to add a with the result
void add(int a)
void sum(int a) :to subtract a from the result
void mul( ) : to multiply a with the result
void div(int a) : to divide result by a
void display() : to display result
void clear() : to clear the result

class Calculator

private int result:


Calculator( )

result=0;

public void add(int a)

result = result + a:

public void sub(int a)

result = result

public void mul(int a)

result = result *

public void div(int a)

result = result / a:

public void display()

Syst em. out. pri


public void clear()
ntln("Result of the calculation" +result):

E.ncapsulation and Inheritance 433


result = 0:

Prog. 2 A number is said to be Palindrome, if it appears to be the same after


reversing its digits", Write a program by using a class with the followino
specitications:
Cass name : Number
Data Members : private nt num:
Meniber Methods :
num with x:
Number(int x) : constructor to initialize
number.
nt reverse(int n) : used to return the reverse of
void palindrome) : to check and print whether the number is palindrome
or not

class Number

private int num:


Number(int x)

num = X;

int reverse(int n)

int rev=0,r;
while(n!=0)

=n%10:
rev=rev*10+r;
n=n/10;

return(rev):

void palindrome()

int k=reverse(num);
if(k==num)
System.out.println("Number is palindrome");
else
System.out.println("Number is not palindrome"):

434 | Understanding Computer Applications with BlueJ-X


Og. numberotvords()int len(Stringint p)
} l=p.lengh): SringStrng piStvatr)mye s;
neturn(c): j=0)}<len(s)i++)
for(int c=0:int reurn): int
4 if(s.charAI()==
C++: )
displuy()
void Members
Methods
Mennber
lnt getlist() Data
: mamie
ClassWrite lenstring
inint Methods name
ntvoid Stringopr(
StMember
rp)inMembers Ptn Wie in
g x)Data (lass
max(int
sum(int mumtbotwords)
a
program
x,int x,int

y)
y): in
: : :cOnsTueOr spcciticaions:
:lollowing
String
: : :private s: :Java
to to: to:privateArray Java to lo Stringopr
coTrespondingelements. nd ind tind
lind ofiaccept with usng
display
and and int and the
the a
return the displaylength to class
the return a<|following
numbers and initialize
elements sum wit h
the the the of
b|| e
maximum
as sum to the
inspecitications: number thstring
ofwell ofboth contain sring
sulation both corresponding
as of p s
of the words with
the l0
maximum he arrays
arrays. integers. X.
and corresponding in
eritance the
clements.
of string
the
435
mport java.util.*:
class Array
private int al| = new int |10):
private int b[|| = new int |10}:
public void getlist)

Scanner in = new Scanner( System.in):


System.out.println("Enter elements in the array:"):
for( int i=0;i<10:i++)

ali<=in.nextlnt):
b[i]=in.nextInt():

int sum(int x,int y)


int z=X+y;
return(z);

int max(int x,int y)

int z;
z=(x>y) ?x: y:
return(z):

void display( )

for(int j=0:j<10,j++)

System.out.println("Sum of corresponding numbers "+sum(aljl.bi):


System.out.println("Maximum of corresponding numbers "+max(a[i].b[jD):
}

Prog. 5 Vidyapati river bridge has a toll booth. Some cars passing through the
bridge stop to pay a toll of 5and are termed as go0d cars but some run
through and do not pay any toll and are termed as bad cars. Write a class
program with the following specifications:
Class name : Tollbooth
Data Members :private statiC int ncars,amount

436 | Understanding Computer Applications with BlueJ-X


display()
vOid badcars()
void goodcars()
void Tollbootcassh
Prog. 6
System.out.println("Total ncars=ncars+1:
("Number amount +=
5:
ncars=ncars+1: pr
amountncar=0: s=0;Tollbooth) ivate
Members Class
Dataname to A static badcars(
display(
voigoodcars( Methods
voi)d voi)dMember
ission)
ay) Member
void void methods d Tollbooth( ) ) :
lecom(double program
Model the
company int
a following ncarS,amount;
class
pays
rates: amount : : :
S,double 1001-
?2000? Sale commission of collected. to: to to
the constructor
2001 1000Up
to
cars printincrease
bridgeincrease
c) with and collected"
: Salecom
passed" the
: :to
to
: : the abOve to within onlyncars to
respectively.
and c private its
find ructor following + + number initialize
displayconst salesmen the by
the double on
amount):ncars); a
10%saleonsale5%
eon
15%salCommission defined ncars l
of and ncars
on by
cars amount
commithsesioninitializesaltospeci
e,com:fications:
mission the period I and
that
sale amount
sale by
and
passed
and value
the with
com according through
amount
0.
with
| s
37
class Salecom

private double sale.com:


Salecomi double s.double c)
sales:

void commission)

if( salec=l(XX0)
come5.0/100,0*sale:
it(sale> 000 && sale <= 2000)
com=10.,0/100.0*sale:
if(sale > 2000)
com=15.0/100.0*sale;
void display)

System.out.println("'Sale value"+sale);
System.out.println("Commission to the salesman" +com);

Prog. 7 Define a class with the following


Class name
specifications:
: Employee
Data Members : String name; float basic;
Member Methods :
void getdata() to accept name and basic pay
Class Salary extends Employee
Data members float da,hra,gross,net
Member functions:
void calculate() : to find the following:
da = 50% of basic
hra = 10% of basic
gross = basic + da + hra
pf = 8.33% of (basic+da)
net = gross - pf
void display() : to display the payslip

438 | Understanding
Computer Applications with BlueJ-X
illustrate Inheritance
to
proeram
in base
class
WA Writen
Coxdjava.Mil,
impor *.

cassEmployee

Stringname:
thoatbasic:
odgetdata)

new Scanner(System.in):
Scannerin =
Sstem.out.println("Enter Employee's name:"):
name=in.nextLine0:
System.out.println(("Enter Employee's basic salary:"):
basic=in.nextFloat(0:

class
Code written in derived
class Salary extends Employee

double da,hra.pf.groSs,net:
void calculate()

da=50.0/100.0*basic:
hra=15.0/100.0*basic:
pf=8.33/100.0*(basic+da);
gross=basic+da+hra;
net=gross-pf:

void display)

System.out.println("Employee's Name: "+nane):


System.out.println("Basic Salary:Rs."+basic);
System.out.println("Dearness Allowance: Rs."+da):
System.out.println"House Rent Allowance:Rs. "+hra):
ystem.out.printin("Provident Fund:Rs."+pf);
System.out.printin("Gross Salary:Rs."+gross);
System.out. println("Net Salary:Rs."+net):

Encapsulation and Inheritance | 439


Compilation and Execution:
Compile both the classes 'Employee and 'Salary' separately. After
Will notice that the class Salary' inherits from class "Employee'. compilation, you
Employee Salary

Create an object of the derived class 'Salary' and select inherited


followed by void getdata(). from Employe
IEmolovee
inherited from Object
Salary

inherited from Employee void getdata()

void calculate()
salary1: void display()
Salary
Inspect
Remove
salary1: Salary

Enter name and salary.

Bluel: Terminal Window - Computer 10


Options

Enter Employee's name:


Ashish Burman
Enter Employee's basic salary:
42000. 00

Press 'Enter key.


Bluel: Terminal Window Computer 10
OptionsS

Enter Employee's nane:


Ashish Burman
Enter Employee's basic galary:
42000.00
Employee's Name: Ashish Eurman
Basic Salary:Rs.42000.0
Dearness Allowance:Rs.21000.0
House Rent A.lcwance:Rs.6300.0
Providert Fund: Ps. 5247.9
Gross Salary:Rs.69300.0
Net Salary:Rs.64032.:

Again, select the object of class 'Salary and right click.


" Select void calculate( )
followed by displav().
Thus, the final result will display on the Terminal
Window'.

440 Understanding Computer Applications with BlueJ-X


Wrie a program by using a class with the
Class name : Product following specifications:
Data Members/lnstance Variables
: To
int pno store product
Stringname : To store name of number
: To the product
int qnty
Member methods
store quanity
void getdata() : To input
product number and name of the
void show) : To display
product number and
proudct
Define another class that name of the product
inherits from Product with the
specifications: following
Class name : Sale
Data members/Instance variables
double rate
double amout
Member method
void input) To accept rate
void calculate() : To find amount by multiplying quantity and rate
void display() : To display amount to be paid

Code written in base class


import java.util. *;
class Product

int pno;
String name:
int qnty;
Scanner in = new Scanner(System.in):
vOid getdata()
System.out.println("Enter the values"):
pno=in.nextInt():
name=in.next():
qnty=in.nextlnt():
void shovw()
System.ou..println("Product number"+pno):
System.ou-fprintln("Product name"+name):
System.out.println("Quantity"+qnty):
/Code written in derived class
class Sale extends Product

doublc rate:
double amount:
Scanner in=new Seanner(System.in);
void input()
System.out.println("Enter rate of the item purchased");
rate=in.nextDouble();

void calculate()

amount=rate*qnty;

void display()
System.out.println("Amount to be paid" + amount);

Chapter at a Glance!
" Encapsulation is defined as wrapping of data and functions as a single unit.
" Apublic member of aclass can be access globally throughout the program.
" The access of private member is restricted within the class visibility.
Amember method declared private can't be invoked outside the class premises.
" A private method is invoked within a member method in nested form.
" Inheritance is a technique according to which a class acquires some features
from other class.

The class whose properties are inherited by another class is refer to the Base'
class whereas, a class that inherits from a 'Base' class is said to be a 'Derived
class.
" A'Base' class is derived into a sub-class by using he kevword
'extends.
" A class that inherits a base, acts as a base for another
class. is knoWI a
Nested' or 'Multilevel Inheritance.
" A class variable or static data member is
declared within a class but outo
any member method by using a
keyword 'static'.
Alocal variable is declared within a method and its accessibility remains
limited under the method block.
The class variables are declared by using the keyword 'static whereas, the
instance variables are declared without the
static' keyword.

You might also like