.
.
Java Technology Fundamentals Newsletter header
    June 27, 2003    

In this Issue

imageJava Programming Language Basics: Overriding and Overloading Methods
imageJava Bits: Simple Search Tool
imageMaking Sense of the Java Class: Class URL
imageProgram Challenge: Overriding static and non-static methods
imageTake an Online Quiz: Test what you learned about overriding and overloading methods
imageJava Workbook: ReadURL Exercise
imageFor More Information: Read articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

.

Java Programming Language Basics

Overriding and Overloading Methods

The Java programming language is object-oriented. Primarily, being object-oriented means that all data is encapsulated within an object, and sending messages to those objects performs operations on that data. Also inheritance plays a large role, where specialized versions of objects can inherit common behavior from more generalized versions of objects. This specialization is often associated with polymorphism so that sending the same message can result in different behavior based upon the receiver of the message or its arguments.

Two often-confused features associated with these aspects of the Java programming language are overloading and overriding.

Overloading is the ability to have a class with multiple methods of the same name where the arguments and return type (method signature) allow the compiler to determine which of the same named methods were meant to be called.

Overriding methods have the same name and identical signatures. When a class is specialized by creating a subclass, to change the behavior of that subclass you replace the behavior of the parent class. This is done by writing a new method with the same name and method signature.

Let's take a look at both in more detail.

As previously stated, to overload a method you have one method of a class that accepts multiple arguments. The most commonly used overloaded method is the println method of System.out. As long as you send one argument to println, the method knows how to print everything, from an int to a long to an Object.

For objects, the code behind the method is just calling the toString method of Object. For the primitives, println knows how to convert each to a Unicode string. So that you can send anything to println, not just String objects, the println method has been overloaded.

Looking at the javadoc for the PrintStream class reveals ten different versions of println, each accepting a different argument set:

    public void println();
    public void println(boolean);
    public void println(char);
    public void println(int);
    public void println(long);
    public void println(float);
    public void println(double);
    public void println(char[]);
    public void println(java.lang.String);
    public void println(java.lang.Object);

By passing in one argument, you get the appropriate behavior.

Here's an example of an overloaded method, named mine. The class below has two mine methods, one that accepts an int and another that accepts a double.

For the int, the method just prints out Integer: with the value following it. For the double, you get Double: and the value.

public class Overload {
        private static void mine(int value) {
                System.out.println("Integer: " + value);
        }
        private static void mine(double value) {
                System.out.println("Double: " + value);
        }
        public static void main(String args[]) {
                mine(1);
                mine(3.141592653589793);
                mine(1L);
        }
}

Notice the three test cases here: the number 1, PI, and the number 1 as a long. Running the program produces the following results:

   Integer: 1
   Double: 3.141592653589793
   Double: 1.0

While the first two answers might be expected, what's up with the third? There isn't a mine method that accepts a long. Absent a method that directly matches the argument(s), the compiler found the best fit.

Since a long variable can't fit in an int variable (without possible loss of precision), the compiler upgrades the long to a double and call the double version of mine. Upcasts can happen automatically where a small variable is converted to a larger one. Downcasts from, say, a double to an int require a casting operation as shown here:

    double d = 3.141592653589793;
    int pi = (int)d;

While this example purposely demonstrates that precision can be lost, if you know the current value of a variable fits into the new space for the datatype, it is OK to perform the down casting operation.

Looking beyond overloading takes us to overriding. Where overloading happens all within a single class definition, overriding requires multiple classes to be involved. Here, let's look at the I/O classes again and the read method.

With the I/O libraries in java.io, no matter what stream you are reading from, the read method allows you to read from that stream. It doesn't matter if the stream is a ByteArrayInputStream, FileInputStream, PipedInputStream, or a SequenceInputStream. In all cases, the read method returns a byte (or -1 on end of stream). The Reader streams work with characters instead of bytes.

Imagine a Shape class where one of the messages it can receive is the ability to calculate the area of itself. When the original designer created the Shape class, only the Circle and Rectangle classes existed, so the area method of Shape was designed as such:

public static final int CIRCLE = 0;
public static final int RECTANGLE = 1;
int type;

public int area() {
   switch(type) {
     case CIRCLE: calcCircleArea(); break;
     case RECTANGLE: calcRectArea(); break;
     default: throw new IllegalArgumentException(
      "Shape not supported: " + type);"
   }
}

While this method supports calling area on all the known figure types when it was written, as soon as someone comes along and adds a triangle, then the old code is broken. A better approach here is to have an abstract area method where all known subclasses define how to calculate their own area.

There is no intermixing of code beyond where it is necessary. And, as soon as a new Shape type is added, that shape defines its own area method and never has to tell anyone else about it.

That's really all there is to overriding and overloading. To try out overriding, see the program challenge below.

.
.

Java Bits

Simple Search Tool

Have you ever created a web page with a lot of detailed information and wanted an easy way for your readers to search and filter page entries based on user-specified keywords? This article explains how to use an HTML form and JavaServer Pages(JSP) technology to do exactly that. And even if you have never wanted to do this, you might find the example demonstration and code walkthrough useful because they cover how to retrieve request values and compare them to values in lines read from a static file.

Read More

.
.

Making Sense of the Java Class

Class URL

Class URL represents a Uniform Resource Locator, a pointer to a resource on the internet. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine.

A URL may consist of a protocol type, a host name, an optional port number, a file name, and a general anchor or reference. The following is an example of a URL:

http://java.sun.com/jdc/onlineTraining/new2java/index.jsp

In this case, the protocol is http, the host name is java.sun.com, the default port of http is 80, the directory name is new2java, and the file name is index.jsp.

The URL class has six constructors you can call to create a URL object:

  • URL(String spec)
    Creates a URL object from the String representation.
  • URL(String protocol, String host, int port, String file)
    Creates a URL object from the specified protocol, host, port number, and file.
  • URL(String protocol, String host, int port, String file, URLStreamHandler handler)
    Creates a URL object from the specified protocol, host, port number, file, and handler.
  • URL(String protocol, String host, String file)
    Creates a URL from the specified protocol name, host name, and file name.
  • URL(URL context, String spec)
    Creates a URL by parsing the given spec within a specified context.
  • URL(URL context, String spec, URLStreamHandler handler)
    Creates a URL by parsing the given spec with the specified handler within a specified context.

Once you have called a URL constructor, then you can call methods from the URL class, which has get methods that return URL properties or a stream, or opens a URL connection:

  • getContent(Class[] classes)
    Gets the contents of this URL.
  • getFile()
    Gets the file name of this URL.
  • getHost()
    Gets the host name of this URL, if applicable.
  • getPath()
    Gets the path part of this URL.
  • getPort()
    Gets the port number of this URL.
  • openConnection()
    Returns a URLConnection object that represents a connection to the remote object referred to by the URL.

The following application demonstrates a URL constructor and methods. Note it will not work through a proxy. You must be on a machine connected to the Internet:

import java.net.*;
import java.io.*;

public class ReadinURL {
  int c;
  
 public ReadinURL() {
   try {
     URL url =
       new URL("http://java.sun.com/j2se/index.html");
       
       URLConnection con = url.openConnection();
       
       System.out.println("File name: " + url.getFile());
       //System.out.println("Content type: " + url.getContent());
       System.out.println("Port: " + url.getPort());
       System.out.println("Host: " + url.getHost());
       System.out.println("Contents: ");
       
       InputStream in = url.openStream();
       
       while ((c = in.read()) != -1) {
         System.out.println((char) c);
         }
         
         in.close();
       } catch (MalformedURLException me) {
         System.out.println("Error " + me);
       } catch (IOException ioe) {
         System.out.println("Error: " + ioe);
         
        }
     }
     
     public static void main(String args[]) {
       ReadinURL tu = new ReadinURL();
      }
 }
.
.

Program Challenge

Overriding static and non-static methods

This month's challenge demonstrates the differences in overriding static and non-static methods. Basically, there is no such thing as overriding a static method. At compilation time, the compiler matches the static method to the class referenced at compile time. It does not match it to the class used at runtime. If a variable is a reference to a superclass type and its static method is called, the superclass' static method is called even if the variable references a subclass type.

  1. To demonstrate, create a pair of classes, one a subclass of the other.
  2. Define two identically named methods in each, naming the static methods staticMethod and the non-static methods instanceMethod.
  3. Make the four methods print out which class and method they are for.
  4. In the test program, create two variables of the parent type and one of the child.
  5. Make one of the parent type variables be an instance of the parent class and the other be the child class.
  6. Assign the child type variable to an instance of the child type. The three lines would look like such:
              Parent p1 = new Parent();
              Parent p2 = new Child();
              Child c = new Child();
    
  7. Next, call the two methods for all things possible and pay particular attention to the calls of p2, where the parent reference variable is an instance of the child. For the static method, you'll see the results for the parent class. For the non-static method, you'll see the results for the child class.

This shows that while you can create static methods with the same name in a subclass, they don't override those of its parent class.

See a possible solution to the Challenge

.
.

Take an Online Quiz

Test what you learned about in this month's issue of Java Technology Fundamentals:

.
.

Java Workbook

ReadURL

Create a program that reads the text contents from a user-specified URL:

.
.

For More Information

Overriding Methods

Overloading and Overriding

When Not to Overload Methods

Class URL

.
.

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.

.
.
.

Reader Feedback

  Very worth reading    Worth reading    Not worth reading 

If you have other comments or ideas for future newsletters, please type them here:

 

Have a question about Java programming? Use Java Online Support.

.
.

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:

- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to developers working with core Java technologies.
- Wireless Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and techniques for developing in the Java 2 Platform, Standard Edition (J2SE)
You can subscribe to these and other JDC publications on the JDC Newsletters and Publications page

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html


Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com

Go to the subscriptions page to subscribe or unsubscribe to this newsletter.

ARCHIVES: You'll find the Java Technology Fundamentals Newsletter archives at:
http://developer.java.sun.com/developer/onlineTraining/new2java/supplements/


Copyright 2003 Sun Microsystems, Inc. All rights reserved. 4150 Network Circle, Santa Clara, CA 95054

Trademark Information: http://www.sun.com/suntrademarks/
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.


Sun Microsystems, Inc.
image
image