advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials :Flexible Object Operation with Java Generics :

Java Generics and Subtyping

Subtyping is a delicate Generics aspect, which may have a start point in the below example:
1: import java.util.List;
2: import java.util.LinkedList;
3: 
4: class subtypingGenerics {    
5:    public static void main(String[] args) {
6:    
7:    List<Integer> numbers = new LinkedList<Integer>();
8:    List<Object> objects = numbers;   
9:    }
10: }
As you can see, line 7 creates a List of Integer using Java Generics. Looking at line 8, you can probably extrapolate the key question of Java Generics subtyping: Is a List of Integer a List of Object? In other words, is a collection of A a collection of B?

Most of the time, the answer is yes—but your compiler will disagree. The compiler knows allowing this code to pass will most likely result in a List containing elements that are not String, down the road.

Furthering this example, you will come across a very important rule—and one that's worth remembering for future sections: If you have X (sub class or sub interface), a subtype of Y, and a generic type declaration (Z), then Z<X> it is not a subtype of Z<Y>.

Wildcards

Wildcards increase Java Generics' flexibility because they permit bounds on the type of parameters and save you when you don’t have specific knowledge of a type parameter's value.

To demonstrate, suppose you want to create a method that displays the elements of a collection. Without Java Generics, your method might look like Listing 1 (the displayCollection method).

Notice how you call the displayCollection method to display a collection of floats and a collection of strings. Now, rewrite Listing 1 using Java Generics—but without wildcards (Listing 2).

Now, you have a serious problem, because Listing 2 compiles with errors! Why?! Because Object is not the supertype of all kind of collections (as you already know from the previous section). This is where wildcards solve the problem.

By using a question mark between angle brackets ("?"), instead of Object type, you provide the real supertype of all kind of collections, which is Collection<?>. This may sound like a minor change, but it is so important that it deserves showing the entire code again (Listing 3).

Author's Note: The Collection<?> formula is known as the collection of unknown and it supports elements of any type.

Now it's time to see how to include bounds in wildcards. First, there are two kinds of bounds:

  • Upper Bound: When a wildcard includes an upper bound, the generic type is a subtype of the bounding class. An upper bound is marked by the extends keyword, as you can see in the below prototype which is one of the ArrayList’s constructors:
    public ArrayList(Collection<? extends E> c)
    
  • Lower Bound: When a wildcard includes a lower bound, the generic type is a super-type of the bounding class. Keep in mind that the super-type relation is reflexive. A lower bound is marked by the super keyword, as you can see in the below prototype, which is the comparator method of the SortedSet class:
    Comparator<? super E> comparator()
    
For a concrete demonstration, suppose you have the following abstract class:
public abstract class abstractCar {    
   public abstract void carInfo();    
}
Suppose also that you have the following subclasses:
public class loganCar extends abstractCar {    
   public void carInfo(){
     System.out.println("-- Logan Info --");
   }
}

public class sanderoCar extends abstractCar {    
   public void carInfo(){
     System.out.println("-- Sandero Info --");
   }
}
Now, imagine that you have a list of abstractCar objects and you want to display the information about every car. At first, you'd probably implement something like Listing 4.

Everything seems fine, but a closer look will reveal a big problem with your application. What happens if you have a collection of loganCar or sanderoCar, not a collection of abstractCar?

Obviously, the application will not pass compile-time because of what you learned in a previous section. To fix this, you can use an upper bound to indicate that the showInfo method can be called with a collection of abstractCar and any other subtype of abstractCar, like loganCar or sanderoCar. Listing 5 shows the application again.

Home / Articles / Flexible Object Operation with Java Generics / 1 / 2 / 3 /Next: Handling Exceptions

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Microsoft Visual Studio 2010 Showcase
 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 39
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Windows 7: From Beta to Final Code in One Year
Google Shows Off Chrome OS, Releases Source
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?
Fedora 12 Takes Aim at Linux Networking
Top Supercomputer Nearly Doubles in Speed
Fedora 12 Linux Tackles Virtualization
Apple Gives iPhone Developers App Status Tracker
Novell Sets OpenSUSE 11.2 Free

Creating Custom Export Filters for StarOffice with XSLT
WPF Wonders: Using DataTemplates
Crystal Reports Family Offers Options for Developers
Avaya Aura Session Manager video
Avaya Aura Overview video
Exploring HTML 5's Audio/Video Multimedia Support
Overriding Virtual Functions? Use C++0x Attributes to Avoid Bugs.
Understanding the Cloud Computing Security Vulnerabilities
Cisco and IBM Target a Greener World
Upgrade to Visual Studio 2010 with the Ultimate Offer

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs