简体   繁体   中英

Java setter and getter?

Everyone knows that Java supports data hiding.

I went for an interview. Then interviewer asked me that if Java supports data hiding by using private as datatype.

He said if we use setters and getters in that class then by using those setters and getters we can get that private data easily.

So how this is supporting data hiding here?

It may be possible that he was trying me catch me in trap. But I could not reply this.

What should I reply for this?

He was arguing that if "Data Hiding" is an OOP principle then aren't we breaking it by exposing via getters and setters. I think he wanted you to spell out the difference in principle between being able to access a data member directly vs. doing it via a getter or setter. In the former case a client of the class can mishandle the data, assign it a value that the class designer has not designed the class to handle (for example set the age of a student as 500). In the latter (using a setter) the class designer has imposed certain restrictions on what values can be assigned to the data. In the age example the setter might be something like:

void setAge(int age) {
if(age<3 || age>100) 
  return;
this.age=age;
}

assuming that students of age below 3 and over 100 aren't allowed. So you are still hiding your data but allowing means to manipulate it in a way consistent with the logic of your module.

Very simple Example:

Version 1 of class could have getter like this.

public int getTotal() {
   return total_;
}

Version 2 could do this

public int getTotal() {
  return a + b;
}

We've changed how the class is implemented, but clients of the class don't need to change as well, because the data is hidden behind a getter.

Data hiding is bad term, better say data encapsulation. In java access to private members is done through accessors and mutators ( getter and setter), it is all about hiding and controlling access to your members so you can control how inner state of instance will be modified.

I think if you mention something about java reflection / metadata -> you will get bonus points

The class fields are hidden, if we declare them private . No doubt (we ignore nasty reflection tricks). If we want to make the values accessible, we provide access methods (getter/setter for example).

But there is no requirement to provide getters and setters for all fields or to name them according to fields (in general).

The class internals (the fields) are perfectly hidden.

protected String name;

public void setName(String newName){
    if(newName.length() > 5) this.name = newName
}

public String getName(){
    return this.name;
}

In this simple case the name attribute can be accessed by its name in this class and in all its children. If you want to set the value of name from an unrelated class than you will have to use the setName() method where you can apply some validation for example.

Here you can find any information you need about this special methods.

Be aware that any property of a class can be accessed if the mutators and accessors are public . This is one of the key points of the Java Bean concept and almost all java frameworks relate to this concept at one point or another.

The support for "data hiding" can be explained by the fact that the getter and setter methods are like gateways to the data.

It is only by convention - the JavaBeans convention to be exact - that it is expected from them to operate on the member they are named after. They could do anything else and it would still be perfectly compilable and legal java.

What you are talking about seems to be Encapsulation . Basically the getters and setters allow you to expose class variables as you like and hide any others. Getters and Setters also allow you to perform any other necessary steps such as validation.

Getters and Setters can have different access modifiers themselves, so you can expose data to certain classes but not others by using different access modifiers.

I bet he was waiting that you will refer to "immutable" types also.

PD. private is no type, it is an access modifier.

也许,他的意思是封装作为信息隐藏。

If you make the setter & getter public/protected/default, then you could access the private members on different levels .. if you make setter&getter private then the data is really hidden. This last way to go makes no sense at all though

您可能会考虑以许多不同的方式实现set / get方法。

As some answers already pointed out, set/get don't have to actually set or return actual members.

For example, let's say you have a Coordinate class with set/get for (x, y). The inner implementation might be based on polar coordinates:

private double radius;
private double angle;

and the get/set for (x, y) do some coordinate transformation with sin and cos.

You could change the implementation of the class to any other system of coordinate at will and still just keep the set/get for (x, y) as public methods.

So, to sum up, my answer to the question would be: the public interface of a class might provide set/get, but the actual implementation can (and should) be hidden by making all members private (or protected). So we could say that having public set/get on private data is "implementation hiding" rather than data hiding.

Data Hiding and Encapsulation are frequently mistaken for security by first time oops learners. Its important to understand that data hiding and encapsulation have nothing to do with security.

These concepts exist to ensure that inheritance of a class A, from class B (class B extends A) does not inherit the "encapsulated" members.

I hope this kinda clarifies your confusion, and also motivates you to read and study more. Your question is very basic to the OOPS concepts. And the interviewer is not trying to corner, you but ask you very basic questions on OOPS. Study hard!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM