Home > Enterprise >  Without a public class. Is it possible to access objects of one class from another?
Without a public class. Is it possible to access objects of one class from another?

Time:02-04

There is two default class. each are in two different files. Files are in same directory. Then it is possible to access one class objects from another. But also I know only public class are accessed by other class. How is that possible?

I think I have mentioned all details.

CodePudding user response:

Not only public attributes are accessible from other classes, in fact. You have 4 different levels of visibility:

  • public: the value of the attribute is accessible from anywhere in the project
  • protected: the value of the attribute is accessible from anywhere within the same package, as well as from the subclasses of this attribute's class
  • default (no keyword): the value of the attribute is accessible from anywhere within the same packages, but not from this attribute's class's subclasses
  • private: the value of the attribute is accessible from within the same class only

In your case, if you didn't specify any modifier, and the classes you're talking about are in the same package, then they're indeed mutually accessible. To prevent that, you should either move them in different packages, or add a private modifier (which should be the preferred option).

CodePudding user response:

Lets say you have


package A;

class A{ }

class D{ }


package B;

class B{ }

class P{ }


Both class A and class B have 'default' access modifier and are in different packages hence they cannot be accessed from another class in different package..i.e class A cannot be accessed by class B and vice versa.

But class D can access class A since both are in the same package. Also class B can access class P for the same reason.

coming to the public access modifer


package C;

public class C{ }

Since the class C has the access modifier of 'public' it can be accessed by classes from other packages BUT it MUST be imported. i.e 'import C' . I hope this answers your doubt.

  •  Tags:  
  • java
  • Related