Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between importing and extending a class?

Tags:

java

What's the difference between importing and extending a class in Java

like image 509
selvam Avatar asked Aug 12 '10 13:08

selvam


1 Answers

Those are two very different things.

Importing a class, is making it so you can use that class without needing to qualify the full name in the current class you are writing.

import java.util.Scanner
// now you can use the Scanner class in your code like so:
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
    }
}
like image 86
jjnguy Avatar answered Oct 02 '22 08:10

jjnguy