ENCAPSULATION & CONSTRUCTOR

ENCAPSULATION /
CONSTRUCTOR

Ques 1 What are instance variable?[2008]
Variable defined in a class are called instance variables.

Ques 2:-What is scope and life time of variables?
Scope of a variable defines the section of source code from where the variable can be accesses. As a general rule. Variable declared inside a scope is not visible to code that is defined outside the scope, thus when you declare a variable with in a scope, you are localizing the variable and protecting it from unauthorized access. The life time of a variable describes how long the variable continues to exist before it is destroyed.

Ques 3 What are access specifiers of an interface?
In java, you can use access specifiers to protect both a class variables and methods while declaring them. i.e. they defines which function or method can make use of a particular method of data. The java language supports four type of access. That are private, public, protected and default

Ques 4 Define role of each type of access specifier
                        OR                              [2008]
Explain any two types of access specifiers.


private :- the variable/method defined as private can be access by member method of the same class.                                                      [2006]
protected :- the variable/method defined as protected  can be access by member method of the same class and its derived class.
public:- the variable/method defined as public can be access by member method of the any class.
Default/ friendly :- when no access specifier is defined then it assumes default access , the variable/method can be accessed from other class of the same package.

Ques 5:- What is the difference between local and instance variable?
The field or variables defined within a class are called instance variables because each instance of the class(object) contains its own copy of these variable. The scope of an instance variable is the whole class definition.
Where as local variable can be used only in the given method of that particular class in which they are declared.

Ques 6: Define constructor. what is its need.?
A  constructor is a member function of a class with the same name as that of its class name. it is defined like other member function of a class. It is used to initialize the data member.
The constructor is needed to initialize the object member in the memory.
Ques 7 What is default constructor?[2006]
Method having same name as class name, used to initialize value when no arguments are pass to it.

Ques 8: What is a parameterized constructor? How is it useful?
Constructor that can take argument are called parameterized constructor. It initializes the data members based on the argument passed to it.

Ques 9: List some special properties of constructor.
i.        Constructor should be declared in the public section of the class
ii.      They are invoked automatically when an object of the class is created.
iii.    They do no have any return and cannot return any value.
iv.    Like other function they can accept parameters
v.      Default constructor do not accept parameter.
vi.    If no constructor is present then the compiler provides a default constructor.

Ques 10: Differentiate between constructor and method                                      [2005]
Constructor
Method
Class name and constructor name should be same
Method can have any name following identifier naming rule
It is used only for initializing data member
Can do any type of calculation or printing.
It is not return type
It has return type
It is called automatically
It has to be called

Ques 11:Explain constructor overloading with example
When two or more constructor with different function signature is defined in a class then it is called constructor overloading.
 Class overload
{
            int a,b;
 overload()
            {
            a=10;
            b=20;
            }
overload(int x, int y)
            {
            a=x;
            b=y;
}}

Ques 12. What are static data members.
Ans:- A static member si a global variable of a class. Such data members are globally available for all the object of the class type. The static data members are usually maintained to store values common to entire class.
  • There is only one copy of this data used by entire class which is shared by all the object of that class.
  • It is visible only with in the class, however its life time is the entire program.
Ques 13. What are static member method?
Ans:- A static member method is a member method which uses only static data members only.

Ques 14 Discuss scope and visibility rule of java.
Ans Java offers following levels of scope and visibility.
i.                    Data declared at the class level can be used by or is visible to all methods in that class.
ii.                  Data declared within a method can be used only in that method or is visible only to that method and is called as local data.
iii.                Variables declared in block. i.e. local variables are available to every method inside that block.
iv.                Variables declared in interior block are not visible outside that block.
v.                  Variables declared in exterior block are visible to the interior block.

Ques 15:- Why is information hiding necessary?
Ans :- Information hiding is necessary because of the following reasons:-
i.                    Users should not be concerned with unnecessary details.
ii.                  Users may do harm if they try to modify the internals of a class.

Ques 16 : Differentiate between Local variable and Global Variable constructor and method
Ans :-
Local Variable
Global Variable
1. A variable declared inside a method or a block is called as local variable.

2. This variable is not accessible outside the method of block in which it is declared
1. A class variable which is available to the entire class and its members is called as global variable.
2. Any method or block inside the class can access these variable.

Ques 17 Discuss hiding of global variable.
Ans :- If a local variable has the same name as the global variable then on using the variable name value of the local variable is accessible i.e. the global variable is hidden. This is called as hiding of global variable.

Ques 18. Difference between class variable and instance variable.
Class Variable
Instance Variable
1. Any data member that is declared once for a class and all the object of this class share this data member is said to be a class variable.
2. A single copy of the variable accessible to all objects is available in the memory.

3.Keyword static is used to declare a variable.
1. A data member that is created for every object  of the class and is not shared is called as instance variable.


2.As many copies of the variable are available in the memory as many number of objects.
3. Normal variable declaration is used.

Ques 19 What is inheritance and how is it useful in Java?                                         [2008]
Ans The process to aquire properties of an existing class is called inheritance.
It provides reusability to a class. It can be useful to add more properties to an existing class without modifying existing class

Ques What does the following means? [2008]
   Employee staff=new Employee()
Ans:= Given statement will create an object names as staff for class Employee.


ques Enter any two varibles through constructor paramenter and write a program to swap and print the values.                                    [2005]
class swap
{
int x,y;
swap(int p, int q)
{
x=p;y=q;
}
void swapping()
{
int t;
t=x;
x=y;
y=t;

System.out.println(x+" "+y);
}
}
class check
{
public static void main(String args[])
{
swap obj=new swap(5,10);
obj.swapping();
}
}


PROGRAM 1 Define a class electricity with
member data:- cno (connection number as integer), cname (consumer name as string),ccap (connection capacity as interger),,unit ( unit consumed), bill as double.
Member function:- electricity(int ,String,int,  int )// //to initialize  cno,cname ccap and unit .
int mincharge() // returns the minimum bill depending upon connection capacity. If ccap is 1 kw then mincharge is Rs150, if ccap is 2kw – 3kw then mincharge is Rs300 , for ccap more then 4 kw then mincharge will be Rs500
void calculate_bill() // calculates bill for first 100 units 1.80 Rs/unit, next 200 units 2.50 Rs/unit, above 300 units  3.20  Rs/unit
void display()// displays bill in proper format.



import java.util.*;
class electricity
{
private int cno,ccap,unit;
private String cname=new String();
private double bill;
public electricity(int cn,String n,int cc,int u)
{
cno=cn;
cname=n;
ccap=cc;
unit=u;
bill=0.0;
}
int mincharge()
{
if(ccap==1)
  return 150;
else if(ccap==2 || ccap==3)
  return 300;
else
  return 500;
}
void calculate_bill()
{
   if(unit<=100)
    bill=unit*1.80;
   else if(unit<=200)
            bill=180+(unit-100)*2.5;
   else
bill=680+(unit-300)*3.20;
  if(bill<mincharge())
   bill=mincharge();
}
void display()
{
System.out.println( "connection number "+cno);
System.out.println( "name              "+cname);
System.out.println( "connection  capacity "+ccap);
System.out.println( "units  "+unit);
System.out.println( "bill "+bill);
}
};
class program
{
public static void main(String args[]) throws Exception
{
electricity ob=new electricity(2,"raju",3,345);
ob.calculate_bill();
ob.display();
}
}
PROGRAM 2 define a class distance with member function with member function feetand inch as integer. Member function aredistance(int ,int)  //to initialize distance in feet and inches. int convert()// returns the distance in inches. void display() display the distance in feet and inches. Use the above class definition to input the dimensions of the room and calculates the volume in inch3 and area in inch2.
class distance
{
private int feet, inch;
public distance(int f,int i)
{
            feet=f;
            inch=i;
}
public int convert()
{
 return feet*12+inch;
}
void display()
{
System.out.println( feet+" feet "+inch+" inch");
}
};
class multiobject
{
public static void main(String args[])
{
distance len=new distance(10,7);
distance wid=new distance(8,9);
distance hei=new distance(9,5);
int l,b,h,a,v;
l=len.convert();
b=len.convert();
h=hei.convert();
a=l*b;
v=l*b*h;
System.out.print( "length is");
len.display();
System.out.print( "Width is");
wid.display();
System.out.print( "height is");
hei.display();
System.out.println( "area is"+a);
System.out.println( "volume is"+v);
}
}
PROGRAM 3 define a class quadratic equation with the member function as a, b and c as integer representing the coefficient of the quadratic equation. quadratic(int,int,int)//initialize the a,b,and c. void properties()// display the properties of the quadratic equations.
void roots() displays the roots of the quadratic equations.
Use above class definition to input coefficient of the quadratic equation and display its properties and roots.
import java.util.*;
class quadratic
{
private int a,b,c;
quadratic( int p,int q,int r)
{
a=p;
b=q;
c=r;
}
void properties()
{
int  q=b*b-4*a*c;
if(q<0)
System.out.println( "roots are imaginary");
else if(q==0)
System.out.println( "roots are real and equal");
else
System.out.println( "roots are real and unequal");
}

void roots()
{
double q;
double x1,x2;
q=b*b-4*a*c;
if(q>=0)
{
x1=(-b+Math.sqrt(q))/2*a;
x2=(-b-Math.sqrt(q))/2*a;
System.out.println( x1+"\t"+x2);
}
}
};
class root
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int a,b,c;
System.out.println( "enter coefficient of quadratic equation");
a=Sn.nextInt();
b=Sn.nextInt();
c=Sn.nextInt();
quadratic obj=new quadratic(a,b,c);
obj.properties();
obj.roots();
}
}
Specify the Output
Consider the following program code:
class scope
{
int value=5;
 void fun1()
{
System.out.println(value+" ");
int value=10;
fun2(value);
System.out.println(value+" ");
fun3();
System.out.println(value+" ");
}
 void fun2(int value)
{
System.out.println(value+" ");
value=20;
System.out.println(value+" ");
}
 void fun3()
{
System.out.println(value+" ");
value=30;
}
};

class check
{
public static void main(String args[])
{
scope obj=new scope();
obj.fun1();
}
}
OUTPUT is:-
5 //value of global variable value is printed
10 //value of argument  variable of fun2() value is printed
20 // modified value of argument  variable of fun2() value is printed
10 //value of local variable of fun1() value is printed
5 // value of global variable value is printed
10 //value of local variable of fun1() value is printed

PROGRAM 4 Write a class with name employee and basic as its data member, to find the gross pay of an employee for the followinf allowences and deduction. use meaningful varibles.
Dearness allowance=25% of basic pay.
House Rent Allowance=15% of basic pay.
Provident Fund=8.33% of basic
Net Pay=Basic Pay+Dearness Allowance++House Rent Allowance
Gross Pay=Net Pay-Provident Fund [2005]

import java.util.*;
class employee
{
String name=new String();
int basic;
employee(String n,int b)
{
name=n;
basic=b;
}
void calc_disp()
{
double hra,da,pf,gs,net;
hra=0.25*basic;
da=0.15*basic;
pf=0.833*basic;
gs=basic+hra+da;
net=gs-pf;
System.out.println("Name\t"+name);
System.out.println("Basic\t"+basic);
System.out.println("Dearness allowance\t"+da);
System.out.println("House Rent Allowance\t"+hra);
System.out.println("Provident Fund\t"+pf);
System.out.println("Net Pay\t"+net);
System.out.println("Gross Pay\t"+gs);
}
}
class emp
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));

String n=new String();
int b;
System.out.println("enter name");
n=Sn.nextLine();
System.out.println("enter basic");
b=Sn.nextInt();
employee obj=new employee(n,b);
obj.calc_disp();
}
}
PROAGRM 5 Define a class employee having the following description
Data members                                   int pan                                    to store personal account number
Instance variable            String name                      to store name
                                                            Double taxincome    to store taxable income
                                                            Double tax                  to store tax that is calculated
Member functions:
input()     store pan number,name,taxable income
calc()       calculate tax for employee
display()   Output details
WAP to copute the tax to the given conditions and give output as per given format
Total Annual Taxable Income                                   Tax rate
Upto rs.100000                                                                                  No tax
From rs.100001 to 150000                                                    10% of income exceeding rs.100000
from rs.150001 to 250000                                                    rs.5000+20% of income exceeding rs.150000
Above 250000                                                                                    rs.25000+30% of income exceeding rs.250000
                                                [2008]
Output:
Pan Number            Name      Taxincome              Tax
….                           …..          ……                         ….
…..                          …..          ……                         …..


import java.util.*;
public class employee
{
int pan;
String name;
double tax;
double taxincome;
public void input() throws IOException
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("enter the name of employee");
name=in.readLine();
System.out.println("enter pan no");
pan=Integer.parseInt(in.readLine());
System.out.println("enter taxable income");
taxincome=Double.parseDouble(in.readLine());
}
public void calc()
{
if(taxincome<=100000)
tax=0;
if(taxincome>=100001 && taxincome<=150000)
tax=(((taxincome-100000)*10)/100);
else if(taxincome>=150001 && taxincome<=250000)
tax=5000+(((taxincome-150000)*20)/100);




else if(taxincome>250000)
tax=25000+(((taxincome-250000)*30)/100);
}
public void display()
{
System.out.println("pan number"+" "+"name" +" "+"Taxincome" + " "+"tax");
System.out.println(pan+" "+name+ " " +taxincome+" " +tax);
}
}









 

PROGRAM TO PRACTICE

·        Classes and Objects-

 

Q1: -   Class  -           Date

Member data             : dd, mm, yy as integer.
date(int d, int m, int y)            //assign d,m,y to dd,mm,yy respectively.
void dispday()              //add suffix with dd 1,21,31 with st , 2,22 with rd, 3, 23 with rd other  with th.
void dispmon()            //displays month in words as jan, feb etc.
void display()             //if date is 11/9/2001 then display 11th September 2003
           
Q2. Declare a class with the following members to store the information about a        Machine in a machine store-
Data members- machine_type (string),machine_no(long), purchase price(double), and      year of purchase(long)
  Functions- void getdata()      to read information about machine
  void   showdata()                  to display the information about the machine.

Q3.   Define a class student with
         Member data: - rollno as int, name as string, mark[5] int array of five elements
average as int, grade as char.
void readdata()            // input rollno, name and marks of five subject.
void calculate_average()         // calculates the average of all subject.
char status()    // retruns P if student scores min 40 marks in all subjects otherwise returns ‘F’
void calculate_grade()            //calculates grade if student is passed in all subject. Otherwise grade is F

Average
>=85
>=65 - <85
>=55 - <65
>=40 - <55
<40
Grade
A
B
C
D
F

void display()               // displays the details of the students.

Q4. Define a class triangle with a member data a, b and c as integer as sides of the
Triangle.
void readdata()            input sides of the triangle.
int ispossible()             retruns 1 if triangle is possible with the given sides.
void area()                   calculates and displays the area of the triangle.
Use above class definition to input three sides of the triangle and display area of the triangle if triangle is possible.

Q5.  Define a class shape with member data asarea ( as double ), perimeter( as double)
with member function shape() which initialize area and perimeter as zero.
void square(int s)                    calculate area and perimeter of square.
void rectangle(int l,int b)        calculate area and perimeter of rectangle.
void equilateral( int a)             calculate area and perimeter of equilateral triangle.
void rightanglet(int h, int b) calculate area and perimeter of right angle triangle.
void circle(int r)          calculate area and perimeter of circle.
void display() display the area and perimeter.
      Write as menu driven program to use above class to find area and perimeter of the  
      given shapes.

QUES 6.There is a class Taxpayer whose class description is given below: Class name:TaXpayer
Data members/instance variables: pan to store the personal account number, name to store the name of a person ,.taxableinc to store the total annual taxable income, tax to store the tax that is calculated
Member functions/methods:Taxpayer( )//constructor, void inputdata( ) //to enter the data for a taxpayer, void displaydata( ) //to display the data for a taxpayer, void computetax( ) //to compute tax for a taxpayer   The tax is calculated according to the following rules: 
TOTAL ANNUAL TAXABLE INCOME RATE OF TAXATION
Up to 60000                -           0%  ,
 Any amount above 60000 but up to 150000             -           5%,
 Any amount above 150000 but up to 500000          -           10%
Any amount above 500000                                        -           15%

Ques 7 Class telcall calculates the monthly phone bill of a consumer. Some of the members of the class are given below:
 Class name:                telcall
Data members/ instance variables:
            phno               : phone number
            name               : name of consumer
            n                      : number of calls made (integer)
            amt                  : bill amount
Member functions/ methods:
            telcall(int x, char y[20], int k) :parameterised constructor to assign values to data members
            void compute() : to calculate the phone bill amount based on the slabs given below
            void display() : to display the details in the specified format

number of calls:                       rate
1 -100     : Rs. 500/- +rental charge only
101 -200  : Rs. 1.00/- per call + rental charge
201 -300  : Rs. 1.20/- per call + rental charge
above 300 : Rs. 1.50/- per call + rental charge 
the calculations need to be done as per the slabs.

QUESTION 8:-
Class employee contains the following member:
Class name:     employee
Data members/instance variables:
empname . : to store the name of employee intempcode : to store the employee code.
basicpay : to store the basic pay of the employee Member functions/methods:
employee() : constructor to initialize all data members/instance variables to null or 0
employee( char n, int p, double q) :parameterised constructor to assign name, employee code                                                                             and basic salary to data members / instance variables.
double salarycal() : to compute and return the total salary of the employee The salary is calculated according to the following rules:
 Salary = basic Pay + HRA +  DA,
HRA = 30% of basic pay,
 DA = 40% of basic pay.
special allowance= if salary is >=10000 then 20% of salary otherwise 15% of salary.

Total salary = salary +special allowance. Specify the employee class giving the details of the two constructors and the function double
salarycal( ) only. You do not need to write the main function
Question 9:-
Create a class salary calculation as given:
Class name:-                            SalaryCalculation
Data member                         name(String type), basic pay, specialalw, coveyanceAlw, gross, pf, netsalary, annualsal
Member function of class:
SalaryCalculation()               - a constructor to assign name of employee name, Basic salary of your choice and conveyance allowance as Rs. 1000
void Salarycal()                      - to calculate other allowance and salaries as given:
                                                Specialalw=25% of basic salary
                                               Gross=basic+specialalw+conveyanceAlw.
                                                netSalary=gross-pf
                                                annualsal=12 month net salary.
void display()                         - to print name and other data member of class with suitable heading.
Write  a main program to create the object of the class. Calculate allowances, salary and print all the data of an employee.
Question 10:
A class dataprocess is defined as follows:
Data members:- N(long integer variable, ch( character variable)
Member function:
Dataprocess(long x, char st)- parameterized constructor to store value of variable x to N, character stored in st to ch.
long FindProduct()    - to find and return product of even digits present in N. do not use (%) operator) for extracting digits. Make suitable use of do-while loop.
void change()- to convert the character stored in ‘ch’ into the opposite cas. Print the original and the new character.
Write a main program to input a number and a character . create the suitable object that activates the parameterized  constructor and by invoking suitable function print the required result.
Question 11;-
Create a class series whose members are as given:
Data members:-         F,S,limit,sum
Member function:-
Series(int n)-               a parameterized constructor to assign 0 to F and 1 to S as the first two terms of Fibonacci series, n to limit as total number of terms to be printed
void printseris() -       to print Fibonacci series[0,1,1,2,3,5,8,13……….limit]

No comments:

Post a Comment

any problem in any program comment:-

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