Tuesday, January 19, 2010

Core Java

Question 1 ) What is Abstraction and Encapsulation ? What is the difference ? Any example ?
Answer:- Abstraction is a technique that help us identify which specific information should be visible, and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.
Also abstraction is the term generally coined with Design where as encapsulation is in relation to implementation.

Eg: Switch (button on/off) is the abstraction and wires are the encapsulation.


Question 2) How can you restrict user not to implement some methods of an interface ?

Answer:- No you cannot. Once you implement an interface your class or subclass must provide its implementation.

Question 3) How do you sort an ArrayList containing UserDefined elements (eg Employees object).
Answer:- Use either of these interfaces methods

java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.

1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1


java.lang.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.

1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1.

Once the method is implemented call
1)Collesctions.sort(list) -> 1st case
2)Collesctions.sort(list, Comparator) -> 2nd case

1 comment: