What is meant by Encapsulation? Can you write a class to
explain encapsulation?

Answer Posted / anjani kumar jha


Binding the Function with its associated data together is
called encapsulation(Tough definition but here is example also)

Think this senario
public class Anjani{
public int size;
public int weight;
...
}
public class Jha {
public static void main (String [] args) {
Anjani a = new Anjani();
a.size = -5; // Legal but bad!!
}
}

if somebody change ur size from -5 to -10; so sad ..........
And now you're in trouble. How are you going to change the
class in a way that
lets you handle the issues that come up when somebody
changes the size variable
to a value that causes problems? Your only choice is to go
back in and write method
code for adjusting size (a setSize(int a) method, for
example), and then
protect the size variable with, say, a private access
modifier. But as soon as you
make that change to your code, you break everyone else's!

The ability to make changes in your implementation code
without breaking the
code of others who use your code is a key benefit of
encapsulation.

Now how u will do this............

Keep instance variables protected (with an access modifier,
often private).
and Make public accessor methods, and force calling code to
use those methods
rather than directly accessing the instance variable.
and For the methods, use the JavaBeans naming convention of
set<someProperty> and get<someProperty>.


so how u will write the code........

full code of incapsulation

class Anjani{
private int size;
public int setSize(int size)
{
this.size=size;

return size;

}
public int getSize()
{
this.size=size;
return size;
}

}
public class jha {
public static void main (String [] args) {
Anjani a = new Anjani();
int x=a.getSize();
a.setSize(10);
System.out.println(a.setSize(10));
}
}

Thanks and Regards
Anjani Kumar Jha
09623154095
CDAC PUNE

Is This Answer Correct ?    3 Yes 5 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

If we allocate the memory using 'new' & de-allocated using 'free' then what will happen?

596


What are the 8 data types in java?

523


Explain the difference between association, aggregation and inheritance relationships.

558


Explain enumeration in java?

569


Explain the importance of finally over return statement?

610






What is the meaning of variables in research?

533


What is the maximum size of byte array in java?

542


What is the difference between variable declaration and variable initialization?

509


Explain the use of sublass in a java program?

599


How do you find the absolute value?

563


What is the purpose of the runtime class in java programming?

570


Which is the class in java?

521


What is the difference between inheritance and encapsulation?

597


How many bytes is a unicode character?

509


Can a method be overloaded based on different return type but same argument type?

547