matt snider
matt snider

Reputation: 4083

Is it possible to extend a Java class with one having the same name

I'm working with a ridiculously large codebase and need to move a file from one package to another. However, I do not have the whole codebase locally, so I am not sure if I have found and updated every reference to the original file. In order to ensure that I don't break anything, I would like to leave the original file, and simply have it extend the new file that I created. Ideally, they'd both have the exact same name. Overtime, I plan to deprecate and remove the old file, but for now this seems like the most robust solution. However, I cannot figure out how to get it to work in Java.

Here is the new class:

package myproject.util.http;

import javax.servlet.http.HttpServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class MyServlet extends HttpServlet
{

    public void service (HttpServletRequest  request,
                         HttpServletResponse response)
            throws ServletException, IOException
    {
        // implementation of service
    }

}

Here is the old class that extends the new:

package myproject.util.net;

import myproject.util.http.MyServlet;

public abstract class MyServlet extends myproject.util.http.MyServlet
{
// this class was deprecated, use myproject.util.http.MyServlet instead
}

Unfortunately, I get the error:

MyServlet is already defined in this compilation unit

Is this possible, or am I going to have to come up with a new name for the parent class.

Upvotes: 7

Views: 5222

Answers (3)

Jack
Jack

Reputation: 133567

You can do it but you need to remove the import statement.

Otherwise the compilation unit will import all the classes declared in your package to be used without the fully qualified name: this means that you wouldn't be able to distinguish between the two MyServlet, this is why it is illegal.

Upvotes: 8

mishadoff
mishadoff

Reputation: 10789

Just remove import and have fully qualified name myproject.util.http.MyServlet

Upvotes: 1

bmargulies
bmargulies

Reputation: 100013

All you need to do is remove the import statement and all will be well.

Upvotes: 0

Related Questions