• Post Reply Bookmark Topic Watch Topic
  • New Topic

In which classes I can declare/create an object of another class?  RSS feed

 
Ranch Hand
Posts: 64
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose there is a class 'A'. I want to declare/create an object of this class in another class 'B'.

So, is there an restriction on the relationship of these two classes to do the above? For example, both classes should belong to the same package, etc.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If class A is public and it has at least one public constructor (or no constructor at all, in which case the compiler automatically provides a public, no-args constructor), then you can create instances of class A anywhere; it doesn't matter whether class B is in another package or in the same package.

Top-level classes can also be package-private (which means they have no access specifier at all), in which case class B must be in the same package. Not only the access specifier of the class matters, but also the access specifier on the constructor(s) of class A.

Nested classes (classes defined inside other classes) can also be protected or private. The usual rules with regard to access specifiers apply.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Nested classes might be an advanced topic, but if you are using inner classes, beware:-
A private inner/nested class is easy to use, but only inside its enclosing type. A public static nested class is also easy to use, but a public inner (= not static) class can be awkward to use outside its enclosing type.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!