Chapter 12

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Chapter 12

ENCAPSULATION AND INHERITANCE


Objects define their interaction with the outside world through the
the outside world; the buttons on the front of your television set, for example, are the
interface between you and the electrical wiring on

the other side of its plastic casing. You press the "power" button to turn the television on
and off.

In its most common form, an interface is a group of related methods with empty bodies.

Different kinds of objects often have a certain amount in common with each other.
Mountain bikes, road bikes and tandem bikes, for

example, all share the characteristics of bicycles (current speed, current pedal
cadence, and current gear). Yet each also defines additional
features that make them different: tandem bicycles have two seats and two sets of
handlebars; road bikes have drop handlebars; some
mountain bikes have an additional chain ring, giving them a lower

gear ratio.
Object oriented programming allows classes to inherit commonly used state and
behavior from other classes.

Let us study the concept of Encapsulation and other related things in terms of Java
Programming
ENCAPSULATION

Encapsulation is a fundamental concept of Object Oriented Programming. Encapsulation helps the


proo^
in concentrating on the relevant details. Encapsulation makes the classes independent and these mfner

reused without modification in other program. be


Qn

The wrapping up of data and functions into a single unit (called class) is known as encapsulation.
Data Hiding
Data hiding enables us to encapsulate an object's data members completely. Data hiding helps in
prevent! the user of an object from being directly accessed by the data members of the class. °9
Ci

Benefits of Encapsulation
Encapsulating related variables and methods into a neat software bundle, is a simple yet very
powerful idea that provides two primary benefits to software developers :
Modularity : The source code for an object can be written and maintained independently of the
source ccc= for other objects. Also, an object can be easily passed around in the system. For
example, You can give your
bicycle to someone else and it will still work.
Information hiding : An object has a public interface which other object can use to communicate
with it But the object can maintain private information and methods that can change at any time
without affecting
the other objects that depend on it. You do not need to understand the gear mechanism of your bike
in order to use it.
Class Member Visibility
As already discussed in the chapter on Classes, there are three levels of visibility of class objects :
(i) public (ii) private (iii) protected

By declaring class members public, these are made accessible to both members and non-member
methods. The data-hiding concept does not allow non-members methods to make access to data
members.
private
When the data members of a class are declared private, they can be accessed only by a member
method of that class. Non-member methods cannot access them. The data remains hidden from
outside world.
•o private is the most restrictive access level.
a private member is accessible only in the class in which it is defined. •o private members are not
inherited by the subclasses.
The following illustration shows how private members are hidden from the outside world :

//Class members' visibility import java.io.*;

ste String empname; pfcete String pfno;


Nob 3t
I

Encapsulation means
wrapping up of data and
methods
Into a eingt
e
\®o. inputd2ta() throws IOException {
unit.
InputStreamReader reader = new InputStreamReader(System.in); 5-fere:: feeder input = new
Buffered Reader(reader);
System.outprintCEnter Name of Employee ::"); sr-r^me = input.readLine ();

System-outprintCEnter PF No. of the Employee ::"); pfno = input.readLine();


System.outprint ("Enter Basic Pay of the Employee ::"); String a = input.readl_ine();
salary = Long.parseLong(a);
}
vokj output data() { System.out.prmtln("======================");
System.outprintln (Name of Employee:::" +empname); System.out.println("PF No :::" +pfno);
System.out.printlnfBasic Pay :::" +salary);
System.out.println ("D.A. +(calculated()));
System.out.printlnfHRA +(calculatehra( )));
System.out.pnntlnf'Gross Pay +(gross pay()));
=

}
private double calculated() { return((0.15 * salary));
}
private double calculate hra() { return ((0.01 * salary));
}
Private double gross pay() {
return (salary +(0.15 * salary)+(0.01 * salary));
}
public class Office {
Public static void main (String args[ ]) throws I Exception { Office Employee employee • new
OfflceEmployee( );
employec.lnputdata (); cmployec.outputdata ( );
4p

In the above program, you will see that the member methods calculated (), calculatehra () and
gros in the public member method output data( ). These member methods calculated (),
and gross pay() are not accessible in the main() method since visibility of private data members
and )(

methods is not possible.


The protected level of class visibility has been explained in the next topic of Inheritance.
SCOPE AND VISIBILITY RULES FOR ACCESS SPECIFIERS
The scope rules of a language are the rules that decide, in which part(s) of the program a particular
p
code or data item would be known and can be accessed therein. I
of
The program part(s) in which a particular piece of code or a data value (e.g., variable) can be
accessed f I known as the piece-of-code's or variable's SCOPE. f
s

Here visibility is a related term. Visibility refers to whether you can use a variable from a given
place / the ' program. I
n

Java offers following levels of scope and visibility : 1 1. Data declared at the class level can be used
by all methods in that class. \
2. Data declared within a method can be used only in that method. ! 3. Data declared within a
method is called local data. I
m 4. Variables that are declared In block i.e., local variables are available to every method inside of
that block. I
5. Variables declared in interior blocks are not visible outside of that block. 6. Variables declared in
exterior blocks are visible to the interior blocks.
Scope and Visibility Rules
Scope
Visibility
Purpose
Public
Visible to all classes
Methods and variables of interest to users of the class
Public classes and
Variables
Protected classes
Protected
visible to classes outside the
package that inherit the class, to third parties who may extend
your class.
Methods and variables of interests
and variables
also to all classes in the package.
default
classes and variables declared with nothing
visible to all classes of the package
Methods and variables involved In
cross-class communication within
the package.
private classes and
private
visible only within the class, not by inheritors, not by other classes
in the package
Variables and methods that should not or would not be changed W
someone extending the class- Proper functioning of the class
depends on them working precisely as written.
variables
Variables declared inside method bodies
or other blocks
local
visible only to the block of the method in which the variables
were declared.
Temporary working variables.
-

instance variables
£25
jesevarfetrtes, ire scope off taaxe va-iabte fe cV>ermted by the access specifier th^t rs
applied to these /arisfcfcs. We naze s 'v*cy oeer a cox* i egfffec The BfeSrne -/these
sarfabfes fe the same as the lifetime of
tie c^sct to «Hdi st befemgs. Cfcgsd arse created <fc oat gtffet for evec Ttey are ciestroyed
by the garbage coBsctor ctf Java vrhen these £re no mars reference to that ofctfect We
sba0 see about 3a/as aromatic
gert-age ctieZ" on,
•* LosSance vafeltz e-e becte-ec'a ciass, but outsfcfe a method, constructor or any btodc
f V/hen a specs is affiocsted fer an object In the heap, a riot for each Instance va-iabie value
is created. •* Instance variafctes are seated when an object is created wSih the use of the
keyword Vie//' and
destroyed vrhen the cfcject is beot'oyad,
*» Instance: /ansbfes boJd vebec that must be 'e'e-ensed by more than one method,
constructor or o-cor or esoert^ oe-ts of en osier's state that must be present throughout the
class.
•* Instance varfe'ofes can be darkened tn class ie/e before or after use. ~v Access trotter-,
!

car. oe given for fctsfcance variables.


** The tnstance var^bte are vis^te for all methods, constructors and block jn tr*e class.
Normally, it Is -erso~me-'Oec so these /eneb.es pn/ate 'access levd). However yisMty for
subclasses can
be gf/en for tf^ese vsnabfes v/2^ the use of access modifiers.
^ 2- te'/ce '#-a'',ab^es hs*/s de^a'.'t -/abas- rcc numbers the default value is 0, for Boo leans
s

it is false anc\'~ss;ec~. 'e'e-e-ces :t 's r. • /abes can be assigned during the declaration or
within the
tegument variables
"'•ese ^-e the variables that a'e defined m the header of constructor or a method. The scope
of th^s- variables k the rne*hod or constructor in v/h»ch they are defined. The lifetime is
limited to the time for which
; executing. Once the method 5r»shes e/eoution, these variables are destroyed.
Local variables
A Iocs! variable ?s the one that ts declared wftfwi a method or a constructor (not in the
header). The scope 3rd rrfe&me are Smites to the method itself.
One important tistiMtian between these three types of variables is that access specifiers can
be applied to '-stance /a^s'-es only and not to argument or local variables.
?

In addition to the local variable defined in a method, we also have variable that are defined
in blocks like an if block and an else block . the scope and lifetime is the same as that of the
block itself.
Local variables are declared in methods, constructors or blocks.
Locai variabies are created when the method, constructor or block is entered and the
variable will be destroyed once rr e/ts d">e method, constructor or block.
Access modifiers cannot be used for local variables.
*+ Local variables are v\s\b\e only within the declared method, constructor or block. There is no default
value for local variables so local variables should be declared and
should be assigned before the first use.
an j
to

class A {
int x = 20; //instance variable
int y = 30; // instance variable
void areamethod(int area) //argument variable
{
//local variable
int perimeter;
perimeter = 2 * (x + y);

area = x * y;
>
//end of class
>
* INHERITANCE
Inheritance is a technique which is used to derive or build new classes from existing one to build object
oriented hierarchy. A class may be derived from one or more classes.
The new classes are called Derived Classes and the existing one is called Base Class.
The derived class inherits the properties of its base class including its member functions and structures
with multiple inheritance. A derived class may have more than one base class and each of which may
have one or
more base classes of its own.
The derived class can add its member functions and data members. It is capable of overriding the
member functions of the base class.
Usefulness of Inheritance
1. Data in existing class can be modified. Developed software can be created.
2. Object oriented hierarchy can be built.
3. Cost of software can be reduced.

Petro Automoblies

Attributes
Engine
Wheels
Seata

Derived class Derived class Derived class


Two Wheelers Two Wheelers Two Wheelers

Tempo Vans
Auto Cars
Attribute Attribute
Motor Scooter Rikshaw Attribute
s s
Cycle Attribute Attribute s
Attribute s s
s

Types of inheritance in java

Class A Base Class

Class B

Base Class
Class A Class B Subclass
Of A

Class B
Class B
Subclass Class B Class C Subclass

of B

Class B

Single Inheritance
When a derived class derives properties from one Base Class, it is called single inheritance. Simply
single inheritance is the property of creating new classes from
an existing base class.
The existing class is called Direct Base Class and the new class is called Singly Derived Class. A
derived class can be defined by specifying the relationship with the base class in addition to its own
details.
The keyword extends is used to inherit the
properties of another class in a given class.
General Syntax of the derived class :
class derived-class-name extends base-class-name
derived class name {
private
//
••••

public
....//data members
....//
protected
....// data members
The visibility mode is optional. The visibility may either be private or public.
CANDID ICSE COMPUTER APPLICATIONS-10
Single inheritance example program In
•i
isvi

class A {
4

!
public void methodA() { System.out.prlntln( f5asc daw mdhod");
M

}
}
class B extends A {
public void methodfi( ) { System.out.printlri("Child class method");
}
public static void main(String args[ ]) {
B obj = new B();
//calling super class method
obj.methodA( );
//calling local method
obj.methodB( );

•o Multiple inheritance is not supported in Java through class.


* DECLARING DERIVED CLASSES
A derived class inherits data members and member functions from its base dass.
It should be noted that base class does not inherit constructor(s) or destructor(s). A derived
dzss teox&i base class when it inherits its properties to other derived class.
Top Class
Base Class (Base Qass for A)
i i
A i i
Derived Class A
(Base Qass for B)

••

OOo
Q

Derived Class B
(Base Qass for C)
Derived Class C
'-Ifc^TTT'T-mTir CT"*miH*.i Ti' lUTj

In the above figure, it is clear that Class A inherits its properties from the top class i.e. Base
Cass.
Class B inherits the properties from A (its base class) plus new properties from top dass.
••

p^ed Oa« C inherits its properties m the top class plus from both A and B.
fr0

class Parent {
private frit count; //private ciass data
public Parent{ ) {
count » 0;
>
void newvalue(int n) {
count » n;
}
void factv3lue(void) {
In the given declaration, member count represents the private data of class. Only base member
function(s) can refer to the count directly.
ParcnU ) is a default constructor. It initializes the count to zero.
value to the count and calculate the value of
Let us derive a new class from Parent.
dass DerivedClass extends Parent { public DerivedClass( ) {
void changecount(int n) { newvalue(n);
factvalue( );
}
}
In the above segment, the derived class has been defined named as DerivedClass. The keyword
extends is used to incorporate the definition of one class into other just after the derived class name.
Therefore, the name of base class Parent comes, from which derived class DerivedClass inherits its
properties.
Public members of a public class remain public in the derived class.
class DerivedClass extends Parent
In this declaration, all public members of parent are public in DerivedClass. If any member is private
in base class Parent, it remains private and the derived class DerivedClass cannot access it.
What you can do in a Subclass
A subclass inherits all of the public and protected members of its parent, no matter what package the
subclass is in. If the subclass is in the same package as its parent, it also inherits the package-
private members of the parent. You can use the inherited members as is, replace them, hide them or
supplement them with new
members :
•o The inherited fields can be used directly, just like any other fields.
^ You can declare a field in the subclass with the same name as the one in the superclass, thus
hiding
it (not recommended).

* You can declare new fields in the subclass that are not in the superclass.
* The inherited methods can be used directly as they are.
v

* You can write a new instance method in the subclass that has the same signature as the
superclass, inus
* You can write a new static method in the subclass that has the same signature as the j 0ne

Hi
n
superclass, thus overridingit.
overnumy .
superclass, thus hiding it.
•» You can declare new methods in the subclass that are not in the superclass.
* You can write a subclass constructor that invokes the constructor of the superclass, either im | P lcj

y
iCitl
or by using the keyword super.
f

tlusiraiion
class Parent {
int count;
Parent() {
count = 0;
void new value(int n) {

count = n;
}
void fact value() { int a;
double factorial; factorial = 1.0;
for(a = 1; a <= count; a++) { factorial = factorial * a;
}
System.out.printlnf'Factorial of" +count + "=" +factorial);
}
}
class derived class extends Parent { void change value(int n) {
count = n;
class Factorial {
public void main() {
Parent pc = new Parent();
derived class dc = new derived class(); pc.newvalue(5);
pc.factvalue ();
dc.changevalue (6);
dc.factvalue ( );
}
}
Output of the Program
Factorial of 6 = 720*0
Multiple Inheritance
H
Multiple Inheritance refers to the concept of one class extending (or inherits) more than one base
class. The inheritance we learnt earlier had the concept of one
base class or parent. The problem with multiple inheritance is that the derived class will have to
manage the dependency on two base classes.
Multilevel Inheritance
Multilevel Inheritance refers to a mechanism in Object Oriented technology where one can inherit
from a derived class, thereby making this derived class the base
- class for the new class.
Multilevel Inheritance example program in Java
/ class X{
public void methodX() {
System.out.println ( class X method");
n

}
}
class Y extends X {
public void method() {
System.out.printlnfclass Y method");
}
}
class Z extends Y {
public void methods() {
System.out.printlnfclass Z method");
public static void main(String args[ ]) {
Z obj = new Z( ); //calling grandparent class method
obj.methodX () //calling parent class method
obj.methodY (); //calling local method
obj.methodZ();
}
}
I

Access Control of Inherited Members


class Box {
protect^
public double width = 5;
protected double height = 6;
public double length = 8;
void getVolume() {
+ width * height * length);
System.out.printlnfVolume is
it

}
}
public class MatchBox extends Box {
class MatchBox can access width, height
and length. All members have public and
protected access.
public static void main(String args[ ]) {
MatchBox mb = new MatchBox( );
mb.getVolume();
System.out.println ("Width of MatchBox 1 is " + mb.width);
System.out.println ("Height of Matchbox 1 is " + mb.height);
System.out.println ("Length of MatchBox 1 is " + mb.length);
}
}
The above program works properly and produces the following output:
Volume is : 240.0
Width of MatchBox 1 is 5.0
Height of MatchBox 1 is 6.0
Length of MatchBox 1 is 8.0
Now let us do some modification in the program
class Box {
public double width = 5;
• width has public access.
• height has protected access.
• length has private access.
i

protected double height = 6;


private double length = 8;
void getVolume() {
System.out.println("Volume is : "+ width * height * length);
}
}
public class MatchBox extends Box {
class MatchBox can
access width,
members but cannot access length,
length has private access.

height
public static void main(String args[ ]) {
MatchBox mb = new MatchBox();
mb.getVolume( );
System.out.println ("Width of MatchBox 1 is " + mb.width);
System.out.println ("Height of MatchBox 1 is " + mb.height);
°
System .out.prlntln(,'l.<;i,yil1 of MatchBox I is" +mb.lengh);
11

}
ft

}
The above program will not work as variable length has been defined with private access.
Subclass matchbox cannot access this variable.

What will be the output of the following program ?


class Encapsulation {
public static int a B 5;
public static void test() {
int a B 15;
i

System.out.println(a);
}
public void output() {
test();
}
}
Answer. In this program, the global variable a has the value of 5 but this /slue fe * fckfetf tte ^
variable with a value of 15 and the result is 15.
This illllustration is based on Single Inheritance.
Answer. import java.io.*; class Emp {
private String empname;
private String pf;
public double salary;
void inputdata(String a, String b, double value) {

empname = a;
pf = b;
salary = value;
}
public void outputdata() {
System.out.println("Name of Employee + empname);
System.out.println("PF NO. + pf); System.out.println( Basic Pay + salary); Single Inheritance
M
When a derived class derives properties from one Base Class, it is called single inheritance. Simply
single inheritance is the property of creating new classes from
an existing base class.
The existing class is called Direct Base Class and the new class is called Singly Derived Class. A
derived class can be defined by specifying the relationship with the base class in addition to its own
details.
The keyword extends is used to inherit the
properties of another class in a given class.
General Syntax of the derived class :
class derived-class-name extends base-class-name
derived class name {
private
//
••••

public
....//data members
....//
protected
....// data members
The visibility mode is optional. The visibility may either be private or public.
Single inheritance example program In
•i
isvi

class A {
4

!
public void methodA() { System.out.prlntln( f5asc daw mdhod");
M

}
}
class B extends A {
public void methodfi( ) { System.out.printlri("Child class method");
}
public static void main(String args[ ]) {
B obj = new B();
//calling super class method
obj.methodA( );
//calling local method
obj.methodB( );

•o Multiple inheritance is not supported in Java through class.


* DECLARING DERIVED CLASSES
A derived class inherits data members and member functions from its base dass.
It should be noted that base class does not inherit constructor(s) or destructor(s). A derived
dzss teox&i base class when it inherits its properties to other derived class.

Top class Base Class


(Base Class for A)

Derived (Base class for B)


Class A
Derived
(Base class for C)
Class B

In the above figure, it is clear that Class A inherits its properties from the top class i.e. Base
Cass.
Class B inherits the properties from A (its base class) plus new properties from top dass.
CANDID ICSE COMPUTER AW^*
••

p^ed Oa« C inherits its properties m the top class plus from both A and B.
fr0

class Parent {
private frit count; //private ciass data
public Parent{ ) {
count » 0;
>
void newvalue(int n) {
count » n;
}
void factv3lue(void) {
In the given declaration, member count represents the private data of class. Only base member
function(s) can refer to the count directly.
ParcnU ) is a default constructor. It initializes the count to zero.
value to the count and calculate the value of
Let us derive a new class from Parent.
dass DerivedClass extends Parent { public DerivedClass( ) {
void changecount(int n) { newvalue(n);
factvalue( );
}
}
In the above segment, the derived class has been defined named as DerivedClass. The keyword
extends is used to incorporate the definition of one class into other just after the derived class name.
Therefore, the name of base class Parent comes, from which derived class DerivedClass inherits its
properties.
Public members of a public class remain public in the derived class.
class DerivedClass extends Parent
In this declaration, all public members of parent are public in DerivedClass. If any member is private
in base class Parent, it remains private and the derived class DerivedClass cannot access it.
What you can do in a Subclass
A subclass inherits all of the public and protected members of its parent, no matter what package the
subclass is in. If the subclass is in the same package as its parent, it also inherits the package-
private members of the parent. You can use the inherited members as is, replace them, hide them or
supplement them with new
members :
•o The inherited fields can be used directly, just like any other fields.
^ You can declare a field in the subclass with the same name as the one in the superclass, thus
hiding
it (not recommended).
CANDID ICSE COMPUTER APPLICATIONS-10 ^
* You can declare new fields in the subclass that are not in the superclass.
* The inherited methods can be used directly as they are.
v

* You can write a new instance method in the subclass that has the same signature as the , 0ne n

superclass, inus
* You can write a new static method in the subclass that has the same signature as the j 0ne

Hi
n
superclass, thus overridingit.
overnumy .
superclass, thus hiding it.
•» You can declare new methods in the subclass that are not in the superclass.
* You can write a subclass constructor that invokes the constructor of the superclass, either im | P lcj

y
iCitl
or by using the keyword super.
f

tlusiraiion
class Parent {
int count;
Parent() {
count = 0;
void newvalue(int n) {

count = n;
}
void factvalue() { int a;
double factorial; factorial = 1.0;
for(a = 1; a <= count; a++) { factorial = factorial * a;
}
System.out.printlnf'Factorial of" +count + "=" +factorial);
}
}
class derivedclass extends Parent { void changevalue(int n) {
count = n;
class Factorial {
public void main() {
Parent pc = new Parent();
derivedclass dc = new derivedclass(); pc.newvalue(5);
CANDID ICSE COMPUTER APPLICATIONS- 10
pc.factvalue();
dc.changevalue(6);
dc.factvalue( );
}
}
Output of the Program
Factorial of 6 = 720*0
Multiple Inheritance
Multiple Inheritance refers to the concept of one class extending (or inherits) more than one base
class. The inheritance we learnt earlier had the concept of one
base class or parent. The problem with multiple inheritance is that the derived class will have to
manage the dependency on two base classes.
Multilevel Inheritance
Multilevel Inheritance refers to a mechanism in Object Oriented technology where one can inherit
from a derived class, thereby making this derived class the base
- class for the new class.
Multilevel Inheritance example program in Java
/ class X{
public void methodX() {
System.out.println( class X method");
n

}
}
class Y extends X {
public void methodY() { System.out.printlnfclass Y method");
}
}
class Z extends Y {
public void methodZ() { System.out.printlnfclass Z method");
public static void main(String args[ ]) {
Z obj = new Z( );
//calling grand parent class method
obj.methodX();
//calling parent class method
obj.methodY();
//calling local method
obj.methodZ();
}
}
I

Access Control of Inherited Members


class Box {
protect^
public double width = 5;
protected double height = 6;
public double length = 8;
void getVolume() {
+ width * height * length);
System.out.printlnfVolume is
it

}
}
public class MatchBox extends Box {
public static void main(String args[ ]) {
MatchBox mb = new MatchBox( );
mb.getVolume();
System.out.println("Width of MatchBox 1 is " + mb.width);
System.out.println("Height of MatchBox 1 is " + mb.height);
System.out.println("Length of MatchBox 1 is " + mb.length);
}
}
The above program works properly and produces the following output:
Volume is : 240.0
Width of MatchBox 1 is 5.0
Height of MatchBox 1 is 6.0
Length of MatchBox 1 is 8.0
Now let us do some modification in the program
class Box {
public double width = 5;
.protected double height = 6;
private double length = 8;
void get Volume() {
System.out.println ("Volume is : "+ width * height * length);
}
}
public class MatchBox extends Box {
class MatchBox can
access width,
members but cannot access length,
length has private access.

height
public static void main(String args[ ]) {
MatchBox mb = new MatchBox();
mb.getVolume ( );
System.out.println ("Width of MatchBox 1 is " + mb.width);
System.out.println ("Height of MatchBox 1 is " + mb.height);
}
}

The above program will not work as the variable length has been defined private acces.
Subclass matchbox cannot access this variable.

What will be the output of the following program ?


class Encapsulation {
public static int a B 5;
public static void test() {
int a B 15;
i

System.out.println(a);
}
public void output() {
test();
}
}
Answer. In this program, the global variable a has the value of 5 but this /slue fe * fckfetf tte ^
variable with a value of 15 and the result is 15.
2. illustration is based on Single Inheritance.
Answer. import java.io.*; class Emp {
private String empname;
private String pf;
public double salary;
void inputdata(String a, String b, double value) {

empname = a;
pf = b;
salary = value;
}
public void output data() {
System.out.println("Name of Employee + empname);
System.out.println("PF NO. + pf); System.out.println( Basic Pay + salary);sclass derivedemp extends
M

Emp {
double grosspay;
double da, hra, pf, netpay;
void calculateda() {
da = 1.5 * salary; System.out.println("DA = +da)j
M

void calculatehra( ) {
hra = 0.1 * salary; System.out.println("HRA =" +hra);
}
void pfdeduction( ) {
pf = 0.12 * salary;
System.out.println ("PF Deduction =" +pf);
}
void calculate gross() {
grosspay = salary + hra + da;
System.out.println ( Gross Salary of Employee =" +grosspay);
n

}
void calculatenetpay() {
netpay = grosspay - pf;
System.out.println ("Net Pay of Employee =" +netpay);
}
}
public class xyz {
public static void main(String args[ ]) {
derivedemp employee = new derivedemp( );
employee.inputdata("Ram Shankar", "R1435", 8000 );
employee.outputdata ();
employee.calculateda (); employee. Calculatehra ( );
employee.calculategross ();
}
This illustration is based on Multilevel Inheritance. Answer, import java.io,*;
class emp {
private String empname;
private String address;
CANDID ICSE COMPUTER APPLICATIONS-10
private String city;
public double salary;
void inputdata(String a, String b, String c, double value) {
empname = a;
address = b;
city = c;
salary = value;
}
public void outputdata( ) {
System.out.println ("==================”);
System.out.println ("Name of Employee -fempname);
System.out.printlnfAddress +address);
System.out.printlnfCity +city);
System.out.printlnfBasic Pay + salary);
}
}
class derivedemp extends emp {
double grosspay;
double da, hra, pf, netpay;
void calculateda() {
da = 1.5 * salary;
System.out.printlnfDA = " +da);
}
void calculatehra() {
hra = 0.1 * salary;
System.out.println("HRA =" +hra);
}
void pfdeduction() {
pf = 0.12 * salary;
System.out.println("PF Deduction =" +pf);
}
void calculategross() {
grosspay = salary + hra + da;
System.out.println("Gross Salary of Employee =" +grosspay);
}
void calculatenetpay() {
netpay = grosspay - pf;
System.out.println("Net Pay of Employee =*' +netpay);

Hierarchical inheritance

It is possible to derive more than one derived class from a single base class. Such type of
inheritance is called hierarchical inheritance.

Class
Base A

Class Base A
B Class
C

Class Class
D E

Object

Use of hierarchical inheritance.


class employ {
Private String empname;;

Private String pfno;


void input data(String a, String b) {
Empname = a;
pfno = b;
public void outputdata() {
System.out.pnntin("========================”);
System.out.println ("Name of Employee:::" +empname);
System.out.printlnfPF No.:::" -f pfno);
}
}
//First derived class starts here
class derivedemp extends employ {
double salary, gross pay; double da, hra, pf, netpay;
derivedemp(double value) {
salary = value;
}
void calculated() {
da = 1.5 * salary;
System.out.println ("DA = " +da);
}
void calculatehra() {
4

hra = 0.1 * salary; System.out.println("HRA = " +hra);


}
void pfdeduct\or)() {
•* IS.'*

pf = 0.12 * salary;
System.out.prir)tln("PF Deduction =" +pf);
}
void calculate gross() {
grosspay = salary + hra + da;
System.out.println (Gross Salary of Employee =" +gross pay);
Asm(

}
void calculatenetpay() {
netpay « grosspay - pf;
System.outprlntln ("Net Pay of Employee =" -f net pay);
}
}
//Second derived class. II inherits properties from base class
class derived second extends employ {
private double bank balance;
derived second(double value) {
bank balance = value;
}
void calculate balance( ) {
System.out.println("Bank Balance of the Employee =" +bank balance);
}
}
Hybrid Inheritance
Hybrid inheritance is a combination of Single and Multiple inheritances. A hybrid inheritance can be
achieved in Java in a same way as multiple inheritance can be. By using interfaces, you can have
multiple as well as hybrid inheritance in Java.
Let us revise
 Inheritance is a technique which can derive or build new classes from the existing class.
 When a derived class derives Its properties from one base class, it is called single
inheritance.
 A derived class can have one of the access specifiers; public, private and protected.
 *

 Private members of the base class remain private in the derived class.
 When two or more classes are derived from one base class, it is called hierarchical
inheritance.
 Three types of inheritance is supported in Java-single inheritance, multilevel inheritance and
hierarchical inheritance.

methods that they expose. Methods form the object's interface with

You might also like