简体   繁体   中英

Packages in Servlets

In Apache tomcat, there was a project created that included Servlets to service the incoming requests. Java class files were kept under

WEBINF\classes\com\example\web

Why do the Java files need to include "package com.example.web" statement so that their compiled classes may be kept in com\\example\\web folder? Tomcat container can easily locate the class files because of the Servlet mappings. Why is this package statement necessary?

Because that's how the language works. You specify exactly which classes you import in order to avoid ambiguities.

Imagine the common scenario when you have two classes with the same name, but different package. Which one should be picked?

For a namespace . Apart from allowing you to have two different classes by the same names (yet making them resolvable), namespaces also help in having a logical group of classes together. I know I'd look at a util package for utility classes, a domain package for entities, a dao package for data-access classes. Imagine having them all under one hood without multiple packages. Wouldn't that be a mess ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM