Object BootCamp - day8
A short discussion, essentially a continuation of yesterday's discussion, on Inheritance marked the beginning of day 8 of the BootCamp. When do we mark methods final? Rarely. But there is an advantage of declaring methods as final - it encourages the "buy" relationship as opposed to inheritance.
We then talked about Cloning in Java. There are two types of cloning - shallow and deep. Why is Cloning necessary? So that you don't give away your data. It is not necessary for immutables. How deep do you need to clone? Till you hit an immutable.
Fred then explained why Cloning is broken in Java. He gave five reasons why cloning is broken in Java:
1. It is Shallow by default.
2. It returns Object, not its own type.
3. The clone method is protected, so when an object buys another, and wants to invoke its clone method, it is not possible to.
4. When we try to call a clone method, the class should have implemented the marker interface Cloneable.
5. The clone method throws a CloneNotSupportedException, a checked exception.
Some alternatives to clone method are:
1. Serialization and deserialization gives a full hierarchy of objects.
2. Copy constructors.
3. We could use reflection and write our own cloning mechanism or
4. Write our own copy method.
But all the above methods also have different drawbacks that makes clone method the best available option.
Fred then started talking about Polymorphism. He chose a very interesting method to explain Polymorphism. He chose four of us and took us outside. He then gave a criteria - height. He then took us inside the class again. He asked the rest of the people to sort us, and that we knew the criteria. So others sorted us by choosing two of us and asking us to decide who was better. After gettingsorted by height, we were given a second criteria and a third. In all these cases, they group sorted the same way without ever knowing about the criteria. This is polymorphism.
We then implemented Polymorphism in our Probability and Rectangle examples. We had an interface Comparable/Orderable which had one method isBetterThan. And then we wrote a max method to find a max from a set of Comparable/Orderable objects.
That was it for the day.
0 Comments:
Post a Comment
<< Home