Ask your own question, for FREE!
Computer Science 15 Online
OpenStudy (anonymous):

I am gonna share two class and wanna learn the reason of security breach.

OpenStudy (anonymous):

I am sorry there are three classes. Why the hacker is able to change private pair?

OpenStudy (asnaseer):

the PetPair class returns a reference to the firstPet and secondPet. the Pet class has a "setter" method that allows the name, age and weight of an instance of a Pet to be changed. therefore, as long as you have a reference to a Pet, you can always modify its name, age and weight. you can block the security breach in PetPair by always returning a "copy" (or clone) of the Pet instances that it holds. that way, any client that modifies the instance that PetPair returns will not change anything in PetPair itself - the client will only be changing the "copy" of the Pet that was returned. I hope this makes sense.

OpenStudy (asnaseer):

an even better solution would be to create a class called, say, ImmutablePet, that has no setter methods, and return an instance of this when getFirst() and getSecond() are called in PetPair().

OpenStudy (asnaseer):

to do that you would first have to extract an interface from the Pet class to represent what a Pet is. it would only contain getters.

OpenStudy (anonymous):

Ok I think i got the reference part.It's sending its reference which hold the old pair's first values and with setter method we override new values to that reference.Nice. But how can i make this copy,can you explain it a little bit more?

OpenStudy (asnaseer):

you currently have: public Pet getFirst() { return first; } this would change to: public Pet getFirst() { return new Pet(first.getName(), first.getAge(), first.getWeight()); }

OpenStudy (anonymous):

Oh great! Instead of sending the reference we just send the values this time. Thank you,asna=)

OpenStudy (asnaseer):

no problem - but as I suggested afterwards, a better solution would be to extract an interface that represent a Pet and return that instead. then you would not need to create any extra objects and your class would be secure.

OpenStudy (asnaseer):

It all depends on whether you have been taught how to use Java interfaces yet or not.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!