Does Java Have a Namespace Like C++?

0
5
Asked By TechExplorer82 On

I'm curious if Java has something similar to C++ namespaces. What I mean is, I want to enforce a style where I have to define variables using a full reference like this:

"Animals.Cat myCat = new Animals.Cat();"

rather than just importing it and using it directly like:

"Import Animals.Cat;

Cat myCat = new Cat();"

Can anyone shed some light on this? Thanks!

1 Answer

Answered By CodeNinja97 On

Java doesn't exactly have namespaces like C++. However, you can achieve a similar effect using packages. If you declare your classes within a package, you can reference them like:

`animal.Cat c = new animal.Cat();`

Imports are just shortcuts, so they're not strictly necessary. You can also use nested classes to create a similar structure, like:

`class Animal { static class Cat {} }

Animal.Cat c = new Animal.Cat();`

So, while you can't enforce strict usage without imports, you have these alternatives.

DevGuru21 -

Got it! But is there a way to enforce that imports aren't used? Also, wouldn't using static classes be problematic with lots of different animals in one file?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.