It's not a secret anymore!*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Importing Vs Subclassing" Watch "Importing Vs Subclassing" New topic
Author

Importing Vs Subclassing

John Paterson
Ranch Hand

Joined: Mar 12, 2012
Posts: 121
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?

regards
John
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

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
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Importing Vs Subclassing
 
Similar Threads
anonymous inner classes
Struts Workflow Extension
Inheritance question
subtype and subclass
Determining the location of the file