Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, December 9, 2011

Abstract Class and Interface

What are the differences between Interface and Abstract class?
Abstract ClassInterfaces
An abstract class can provide complete, default code and/or just the details that have to be overridden.An interface cannot provide any code at all,just the signature.
In case of abstract class, a class may extend only one abstract class.A Class may implement several interfaces.
An abstract class can have non-abstract methods.All methods of an Interface are abstract.
An abstract class can have instance variables.An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.An Interface visibility must be public (or) none.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
An abstract class can contain constructors .An Interface cannot contain constructors .
Abstract classes are fast.Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.


When should I use abstract classes and when should I use interfaces?
Use Interfaces when…
  • You see that something in your design will change frequently.
  • If various implementations only share method signatures then it is better to use Interfaces.
  • you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when…
  • If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
  • When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
  • Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies

Wednesday, December 7, 2011

What It Means If You Don't Override equals()



There's a potential limitation lurking here: if you don't override a class's equals()
method, you won't be able to use those objects as a key in a hashtable and you
probably won't get accurate Sets, such that there are no conceptual duplicates.
The equals() method in class Object uses only the == operator for comparisons,
so unless you override equals(), two objects are considered equal only if the two
references refer to the same object.

Let's look at what it means to not be able to use an object as a hashtable key.
Imagine you have a car, a very specific car (say, John's red Subaru Outback as
opposed to Mary's purple Mini) that you want to put in a HashMap (a type of
hashtable we'll look at later in this chapter), so that you can search on a particular
car and retrieve the corresponding Person object that represents the owner. So you
add the car instance as the key to the HashMap (along with a corresponding Person
object as the value). But now what happens when you want to do a search? You want
to say to the HashMap collection, "Here's the car, now give me the Person object
that goes with this car." But now you're in trouble unless you still have a reference
to the exact object you used as the key when you added it to the Collection. In other
words, you can't make an identical Car object and use it for the search.
The bottom line is this: if you want objects of your class to be used as keys for a
hashtable (or as elements in any data structure that uses equivalency for searching
for—and/or retrieving—an object), then you must override equals() so that two
different instances can be considered the same. So how would we fix the car? You
might override the equals() method so that it compares the unique VIN (Vehicle
Identification Number) as the basis of comparison. That way, you can use one
instance when you add it to a Collection, and essentially re-create an identical
instance when you want to do a search based on that object as the key. Of course,
overriding the equals() method for Car also allows the potential that more than
one object representing a single unique car can exist, which might not be safe in your design. Fortunately, the String and wrapper classes work well as keys in
hashtables—they override the equals() method. So rather than using the actual
car instance as the key into the car/owner pair, you could simply use a String that
represents the unique identifier for the car. That way, you'll never have more than
one instance representing a specific car, but you can still use the car—or rather, one
of the car's attributes—as the search key.
Implementing an equals() Method
Let's say you decide to override equals() in your class. It might look like this:
public class EqualsTest {
public static void main (String [] args) {
Moof one = new Moof(8);
Moof two = new Moof(8);
if (one.equals(two)) {
System.out.println("one and two are equal");
}
}
}
class Moof {
private int moofValue;
Moof(int val) {
moofValue = val;
}
public int getMoofValue() {
return moofValue;
}
public boolean equals(Object o) {
if ((o instanceof Moof) && (((Moof)o).getMoofValue()
== this.moofValue)) {
return true;
} else {
return false;
}
}
}


How HashMap works in java .

Friday, November 18, 2011

Threading in Java

Difference between interface and class

First, an interface can only contain abstract methods and/or static final variables (constants). Classes, on the other hand, can implement methods and contain variables that are not constants.

Second, an interface cannot implement any methods. A class that implements an interface must implement all methods defined in that interface.

An interface has the ability to extend from other interfaces, and (unlike classes) can extend from multiple interfaces.

Furthermore, an interface cannot be instantiated with the new operator; for example, Runnable a=new Runnable(); is not allowed

Exceptions in Java


Throwable has two direct subclasses, Exception and Error.
        Exceptions (members of the Exception family) are thrown to signal abnormal conditions that can often be handled by some catcher, though it's possible they may not be caught and therefore could result in a dead thread.
        Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle.

In general, code you write should throw only exceptions, not errors.Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself.

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

In Detail :

http://www.javaworld.com/javaworld/jw-07-1998/jw-07-exceptions.html?page=1a

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/RuntimeException.html

Monday, November 7, 2011

HashMap and Hashtable

HashMap:

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor.
The capacity     -  number of buckets in the hash table,
Initial capacity  - the capacity at the time the hash table is created.
The load factor - measure of how full the hash table is allowed to get before its capacity is automatically increased.

When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets

HashTable:
Wont permit null keys and null values.
Synchronised(thread safe).

Concurrent HashMap:
Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.
If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

Friday, November 4, 2011

Marker Interfaces

Cloneable : 
public interface Cloneable
 --> classes that implement this interface should override Object.clone(protected)
 with a public method. 
 (Cant reduce the visibility of the method inherited).
 --> This interface does not contain the clone method.Therefore, it is not possible
 to clone an object merely by virtue of the fact that it implements this interface. 
Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.
protected Object clone() throws CloneNotSupportedException 
     By convention, the object returned by this method should be independent of this object (which is being cloned). To achieve this independence, it may be necessary to modify one or more fields of the object returned by super.clone before returning it. Typically, this means copying any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing the references to these objects with references to the copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified. 
          The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable and that the return type of the clone method of an array type T[] is T[] where T is any reference or primitive type. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.
         The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.

Comparable:
 public interface Comparable<T>
          Lists (and arrays) of objects that implement this interface can be sorted  automatically 
by Collections.sort (and  Arrays.sort). Objects that implement this  interface can be used as 
keys in a sorted map or as  elements in a sorted set, without the need to  specify a comparator.
        The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

int compareTo(T o)
Compares this object with the specified object for order. 
Returns a  negative integer, zero, or a positive integer as this object is less  than, 
equal to, or greater than the specified object. 
Throws:  
NullPointerException - if the specified object is null  
ClassCastException - if the specified object's type prevents it from being compared to this object.


Comparator : 
Interface Comparator<T>
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
      Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering 
      Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.
For example, suppose one adds two elements a and b such that (a.equals(b) && c.compare(a, b) != 0) to an empty TreeSet with comparator c. The second add operation will return true (and the size of the tree set will increase) because a and b are not equivalent from the tree set's perspective, even though this is contrary to the specification of the Set.add method.
     Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation.
int compare(T o1,T o2)
           Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. 
Throws: 
NullPointerException - if an argument is null and this comparator does not permit null arguments 
ClassCastException - if the arguments' types prevent them from being compared by this comparator.