jQuery in Action, 3rd edition
The moose likes Java in General and the fly likes Importing Vs Subclassing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Importing Vs Subclassing" Watch "Importing Vs Subclassing" New topic

Importing Vs Subclassing

John Paterson
Ranch Hand

Joined: Mar 12, 2012
Posts: 168
Hi Folks,

What is the difference between importing a class and subclassing it? Either way I gain access to the members of the 'other' class right?

Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10768

No you dont.

Importing just tells the compiler you are going to use the package/class in your code.
Subclassing is usually done, when you need to add some functionality. Even if you subclass, you do not always gain access to members with private scope.

Check out http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html and http://docs.oracle.com/javase/tutorial/java/concepts/inheritance.html

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

Importing has precisely zero effect on the generated byte code. It's just syntactic sugar to save typing and keep your code less cluttered. All it does is tell the compiler that when you write "X" you really mean "com.a.b.c.X".

Subclassing is totally unrelated to that, but it's not what you seem to think it is either. We don't subclass X to get access to members of X. (The only thing that would give us that we didn't already have would be those members which are protected, and there aren't usually that many of those anyway.) We subclass in order to specialize a type--to implement or change the behaviors or certain methods. The main purpose of inheritance is not code sharing.
wood burning stoves
subject: Importing Vs Subclassing
It's not a secret anymore!