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
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.
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?