Friday, January 24, 2014

Difference Between import(using) and extends(implement)

Importing a class, makes you to use that class without needing to mention the full name in the current class you are writing.

import java.util.Scanner
// now you can use the Scanner class in your code:
Scanner stdin = new Scanner(System.in);
//instead of having to do
java.util.Scanner stdin = new java.util.Scanner(System.in);


Extending a class is creating a new class that is a subclass of some other class. This will allow you to add or change functionality of the class you are extending.

// this is a very contrived example
public class EmptyList extends ArrayList {
@Override
public boolean add(Object o){
return false; // will not add things to a list
}
}


We used extend in order to use the polymorphism feature. When we extending a class we can access the class data member & functions(methods) but by import a class we can access the class and we can't use members and methods of the class without creating instant for that class.

In UML conventions extending satisfies IS A relationship where just importing satisfies only use / Has A relationship.

No comments:

Followers

Link