可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This is basic question but still i don't understand encapsulation concept . I did't understand how can we change the properties of class from other class.because whenever
we try to set the public instance value of class we have to create object of that class and then set the value.and every object refer to different memory.so even if we change
the instance value this will not impact to any other object.
Even I try to change using static public instance value also i am not able to change the class property value.
Example is given below
// Employee class
public class Employee {
public static int empid;
public static String empname;
public static void main(String[] args) {
System.out.println("print employe details:"+empid+" "+empname);
}
// EmployeeTest class
public class EmployeeTest {
public static void main(String[] args) {
Employee e = new Employee();
e.empid=20;
e.empname="jerry";
Employee.empid=10;
Employee.empname="tom";
}
}
}
Every time I run Employee
class I am getting same value
print employe details:0 null
Even though I am not following encapsulation concept and I am not able to change public instance value of employee class.Please help me to understand the concept where i am going wrong.
回答1:
Yeah, this can be a little confusing sometimes. Let's go step by step: First, you need to understand
- What is encapsulation and why is it used.?
Encapsulation is one of the four fundamental OOP concepts.Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
Take a small example:
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}
The above methods are called Accessors(aka getters and setters). Now you might ask,
- Why should you use accessors..?
There are actually many good reasons to consider using accessors rather than directly exposing fields of a class.Getter and Setters make APIs more stable.
For instance, consider a field public in a class which is accessed by other classes. Now later on, you want to add any extra logic while getting and setting the variable. This will impact the existing client that uses the API. So any changes to this public field will require change to each class that refers it. On the contrary, with accessor methods, one can easily add some logic like cache some data, lazily initialize it later. Moreover, one can fire a property changed event if the new value is different from the previous value. All this will be seamless to the class that gets value using accessor method.
There are so many tutorials and explanations as to how and what are they. Google them.
As for your, current problem:
- You have two different classes, each with a main. That is wrong. They will have different properties.
- Code change suggested by @Subhrajyoti Majumder is the correct one. Check the answer for solving the problem.
In the meantime, read up on
for a better understanding of the concepts. Hope it helps. :)
回答2:
It seems you are running two different classes separately and assuming the changes done to attributes when you run EmployeeTest
will reflect in Employee
run. Note that changes will reflect in the same JRE instance. Excuse me in case i have misunderstood your problem.
EDIT: As per the user input. Here is the code how you can access and update the static member values:
class Employee {
public static int empid;
public static String empname;
public static void main(String[] args) {
System.out.println("print employe details:" + empid + " " + empname);
}
}
// EmployeeTest class
public class EmployeeTest {
public static void main(String[] args) {
Employee e = new Employee();
e.empid = 20;
e.empname = "jerry";
Employee.empid = 10;
Employee.empname = "tom";
Employee.main(null);
}
}
回答3:
public static
field's are associated with class not with object, it break Object's encapsulation rule.
Employee
class with two encapsulated field empid & empname
.
public class Employee {
private int empid;
private String empname;
public int getEmpid(){
return this.empid;
}
public void setEmpid(int empid){
this.empid = empid;
}
...
}
public class EmployeeTest {
public static void main(String[] args) {
Employee e = new Employee();
e.setempId(1);
Employee e1 = new Employee();
e1.setempId(2);
}
}
Documentation for better understanding on encapsulation
回答4:
The concept of encapsulation is a design technique that relates with information hiding. The underlying principle is to provide protected access to the class attributes, through a well designed interface. The purpose of encapsulation is to enforce the invariants of the class.
To follow on your example consider the interface of this class:
class Employee
private final String firstName;
private final String lastName;
public Employee(final firstName, final lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getName() {
return firstName + " " + lastName;
}
}
Note that by declaring the attributes as private this class restricts clients from directly accessing the state of employee object instances. The only way for clients to access them is via the getName() method. This means that those attributes are encapsulated by the class. Also note that by declaring the attributes as final and initializing them in the constructor we create an effectively immutable class, that is one whose state cannot be modified after construction.
An alternative implementation would be the following:
class Employee
private String firstName;
private String lastName;
public Employee(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getName() {
return firstName + " " + lastName;
}
public String setName(String firstName, String lastName) {
if (firstName == null) {
throw new IllegalArgumentException("First name cannot be null");
}
if (lastName == null) {
throw new IllegalArgumentException("Last name cannot be null");
}
this.firstName = firstName;
this.lastName = lastName;
}
}
In this example the object is not immutable but its state is encapsulated since access to it takes place only through accessors and modifiers. Note here how encapsulation can help you protect the invariants of the object state. By constraining modifications through a method you gain a better control of how the object state is modified, adding validations to make sure that any modifications are consistent with the specification of the class.
回答5:
Encapsulation means combining data and code together(class). The main purpose of encapsulation is you would have full control on data by using the code.
class Encap{
private int amount;
public void setAmount(int amount)
{
this.amount = amount;
}
Here, you can set the amount using the setAmount method, but value should be more than 100. So, i have the control on it.
public void setAmount(int amount)
{
if(amount>100)
this.amount = amount;
}
回答6:
encapsulation =VARIABLES(let private a,b,c)+ METHODS(setA&getA,setB&getB....)
we can encapsulate by using the private modifier.
let consider your created one public variable and one private variable in your class...
in case if you have to give those variables to another class for read-only(only they can see and use not able to modify) there is no possibility with public variables or methods,but we can able to do that in private by providing get method.
so Your class private variables or methods are under your control. but IN public there is no chance....i think you can understood.
回答7:
Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class.
Access to the data and code is tightly controlled by an interface.
Encapsulation in Java is the technique of making the fields in a class private and providing access to the fields via public methods.
If a field is declared private, it cannot be accessed by anyone outside the class,
thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
Real-time example: cars and owners. All the functions of cars are encapsulated with the owners. Hence, No one else can access it..
The below is the code for this example.
public class Main {
public static void main(String[] args) {
Owner o1=new Car("SONY","Google Maps");
o1.activate_Sunroof();
o1.getNavigationSystem();
o1.getRadioSytem();
}
}
//Interface designed for exposing car functionalities that an owner can use.
public interface Owner {
void getNavigationSystem();
void getRadioSytem();
void activate_Sunroof();
}
/*
Car class protects the code and data access from outside world access by implementing Owner interface(i.e, exposing Cars functionalities) and restricting data access via private access modifier.
*/
public class Car implements Owner {
private String radioSystem;
private String gps;
public Car(String radioSystem, String gps) {
super();
this.radioSystem = radioSystem;
this.gps = gps;
}
public String getRadioSystem() {
return radioSystem;
}
public void setRadioSystem(String radioSystem) {
this.radioSystem = radioSystem;
}
public String getGps() {
return gps;
}
public void setGps(String gps) {
this.gps = gps;
}
@Override
public void getNavigationSystem() {
System.out.println("GPS system " + getGps() + " is in use...");
}
@Override
public void getRadioSytem() {
System.out.println("Radio system " + getRadioSystem() + " activated");
}
@Override
public void activate_Sunroof() {
System.out.println("Sunroof activated");
}
}
回答8:
of course, change on one object will not impact on another object. suppose you have a class student and all the children at your school are it's objects. if one leaves the school, this doesn't mean, every other student (object of student class) should leave the school too.
Encapsulation is the concept of having your class variables as private, so that no one can directly play with your data members from outer world. but you provide the public method, to let the outer world play with your data member, the way you want them to. the nice coding example of encapsulation is given above by Subhrajyoti Majumder.
(static members are same for all objects of the class. eg: static count variable, to count the number of student class objects. (number of students at school)).
Edit as you asked for:
Example:
public class student{
public String name;
public student() {}
}
and in your main function, outer world can play with your class attributes as:
student s = new student();
s.name = "xyz";
let's suppose, you don't want to let the outer world change your name attribute of object. then you should make name 'name' as private, and provide a public method to only view the name (get).
Example:
public class student{
private String name;
public student() {}
public String getName(){
return this.name;
}
}
and now in your main method, you can only get the name object, and can't set it to new value, like you could do in first example.
student s = new student();
String sname = s.getName();
and if you try:
s.name = "newname";
compiler will not allow you that. since you don't have permission to access the private members.
回答9:
The reason you are getting the output "print employe details:0 null" when running the Employee class is because those variables are not initialized. That is, you do not assign any values to them within the Employee class.
Whatever you do within the EmployeeTest class will not affect the values of the variables in Employee the next time it is run. Consider each run of a Java program a "clean slate".
On the point of encapsulation, you really should not be using the static
keyword. If you are going for encapsulation check out the other answer to this question, it has a nice code sample for you to use.
回答10:
The encapsulation is an OOP concept.
The class is considered like a capsule that contains data + behavior.
The data should be private and should be accessed only using public methods called getters and setters.
You may check this encapsulation tutorial for more informations about this concept.
回答11:
ENCAPSULATION is mechanism of wrapping methods and variables together as a single unit. for example capsule i.e. mixed of several medicines.
variables of a class will be hidden from other classes as it will be declared private, and can be accessed only through the methods of their current class
To achieve encapsulation in Java −
* Declare the variables of a class as private.
* Provide public setter and getter methods to modify and view the variables values.
* The Java Bean class is the example of fully encapsulated class.
回答12:
Do you mean to say that the value of empid should be 10 and empname tom instead of 0 and null,
if yes then-:
1)memory to the variables is allocated at run time , and also deallocated after the program is terminated.
2)Hence if you think that once if you give 10 to empid it should always be 10, it is not so , because empid is just a reference to a memory which is storing "10".
3)So by deallocation , i mean that empid is no longer pointing to memory area storing 10, after the program terminates
4)whenever you execute a new program , the empid is now pointing to other memory area , and that memory is allocated the the default value according t the respective datatype,in case of static variable.
hence always 0 and null.