This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 5 years ago.
I have a package that contains two classes. Private variable share is located in class A and that variable can be accessed only by these two classes, A and B, and can't be accessed by importing the package. Is it possible to achieve this?
// A.java
class A {
private static String share;
}
// B.java
class B {
public String myMethode() {
// do something with share
}
}
You cannot achieve it directly.
There are visibility levels in Java:
public - visible from any other classes
protected - visible in all classes who extend a class
so if in Class A you have
class A {
protected String share;
}
it will be visible in class B extends A, class C extends B and so on...
then there is a possibility to create another class D extends A and share will be visible in it. Unless class A is final, but with that you cannot have needed class B extends A
package visible
package com.foo.myclasses;
class A {
String share;
}
with that share will be visible in all classes in the package com.foo.myclasses
So still there is a way to create a class in the same package and share will be visible in it.
You may do a Work around to achieve that.
make private String share in class A
create protected getShare() (or package visible) method
and check the class like
protected String getShare() {
if (this.getClass().getName().equals("com.foo.myclasses.A") or this.getClass().getName().equals("com.foo.myclasses.B")) {
return share;
} else
{
throw new IllegalAccessException(this.getClass().getName() + " is not allowed to access share);
// or return null
}
}
But it is about access to the value of share at run time. Nothing prevents access (as above) in the code. Code will compile, but throws exception at run time.
It is what it is.
Related
This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 5 years ago.
I am confused with access specifiers in Java.. I have a code with 2 different packages in Java.. But it displays an error every time I run it.. Here's is the code for the class which is calling the class using import from another package..
package p2;
import p1.Testing;
class Pqr extends Testing{ // extending the class
void hey(){
System.out.println("Something");
}
}
class Xyz{
public static void main(String args[]){
Pqr t1 = new Pqr(); // Class from another package.
System.out.println(t1.find("Mississippi","p"));
t1.hey();
}
}
Code for class which is being subclassed from package p1..
package p1;
class Testing{
protected static boolean find(String a,String b){ // Protected specifier
boolean ans = false;
for(int i=0;i<a.length();i++){
String m = a.charAt(i) + "";
if( m.equals(b)){
ans = true;
}
}
return ans;
}
public static void main(String args[]){
// Main Class
}
}
But when I run the code i get an error "Testing is not public in p1; cannot be accessed from outside package"..
I learned in this thread that we can use protected method between different packages but by extending it by another class.. In Java, difference between package private, public, protected, and private
Thanks in advance.
You don't have an access to the top-level class (in your case it's Testing), so you can't have an access to its members, no matter what are its access modifiers. You need to make Testing public to make its protected members visible from outside of its package to classes extending Testing. You can read more about it in Java tutorial. Here is a part about access modifier of Testing class:
A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package
And the part about your find() method:
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
But to make use of protected members of class contained in another package, the class itself containing it need to be visible in another packages (it needs to be public).
Take a look at this Java tutorial for more informations about access modifiers:
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
This question already has answers here:
Why protected can be access in same Package without inheritance in java? [duplicate]
(1 answer)
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 8 years ago.
Why do protected attributes in a Java class can be accessed by the other classes of the same package ?
I thought it was only accessible through inheritance.
A.java
package abc;
class A {
protected int attr1;
}
B.java
package abc;
class B {
B() {
A obj = new A();
obj.attr1 = 2;
}
public static void main(String[] args) {
B obj2 = new B();
}
}
Because that was the decision of the language creators.
Methods/fields with the protected access modifier are accessible
by both classes from the same package as the class defining them,
as well as by subclasses of the class defining them. And of course,
they are also accessible by the defining class itself.
You should think about it this way: protected is a kind of public access level. Protected members are a part of public API in classes designed for extension. It would make no sense for a member accessible to the API client to be inaccessible to the API implementation, especially at a place where another member with default access level (which is non-public) is accessible.
This question already has answers here:
Do objects encapsulate data so that not even other instances of the same class can access the data?
(7 answers)
Closed 8 years ago.
I wrote the following class to fiddle around with Comparable/Serializable interfaces.
package testpro;
public class SerialTest implements Comparable {
private int circleSize = 10;
private int getCircleSize() {
return circleSize;
}
#Override
public int compareTo(Object o) {
SerialTest object = (SerialTest) o;
if(getCircleSize()>object.getCircleSize()){ // I can access object.getCircleSize() here, but it's private.. why?
return 1;
}
else if(getCircleSize()<object.getCircleSize()){// I can access object.getCircleSize() here, but it's private.. why?
return -1;
}
else{
return 0;
}
}
}
I'm passing an Object o to compareTo() method, but getCircleSize() is private. So how is that possible, that I've got an access to this?
I'm pretty sure C++ wouldn't let it go.
Private means accessible from the same class only. And you are in the same class, after casting Object o to SerialTest object.
Private method are accessible within the class itself. Since both methods residing the same class, there no problem of accessing it.
The private modifier specifies that the member can only be accessed in
its own class.
Check here for more details
private are not accessible by other classes. But within the class it is accessible for programming. Such as your code, you can use all the private identifiers or methods within the class while generating a result.
C++ also provides this function. You can easily use private method inside a class or method, to generate a response for a function call. It is simple and is legal!
You access to private member from same class. You override method compareTo() and in it you are accessed to your private member.
You can't do this with private member without accessor from each other class.
You can learn this from this link.
I tried following piece of program and I came to know we can access default/package level instance variable.
I want to understand why it is allowed in java.
1.
package com.test;
class A {
public int i = 10;
}
2.
package com.test;
public class B extends A{
}
3.
package com.child;
import com.test.B;
public class C extends B{
public int getI(){
return this.i;
}
public static void main(String[] args) {
System.out.println(new C().getI());
}
}
I'm able to run this program successfully. What I want to understand is how it possible to access default access variable from another packkage.
Because it extends B which extends A.
B inherits all public members from A, regardless A's own visibility. That's why C sees the member too.
This is of course quite confusing. The root problem is that a public class extends a non-public class. Maybe the language should forbid that.
there are 4 different access levels: public, private, protected and package-private. Public is visible to everything, outside package even. Private is visible only inside class. Protected is visible to class and to all classes, that extends it. Package-private is default (when you don't specify any of others), and it is visible to all classes within one package, where the variable is initialized
I understand that protected access means that one can access the member within the package and any subclass, regardless of the package. What I find hard to understand is that, in a subclass, when I create an object of the class which has the protected member, I get a "not visible" error?
This is demonstrated by the following code (which is an expanded version based on an answer by YiFan Wu). Note that I have the same lines of code inside and outside of the package. Thus I have two questions:
Why does using the object change everything?
This object access difference does not happen within the package i.e. see test() in class A1.
package a;
public class A{
protected int a;
}
class A1{
public void test(){
A ref = new A();
ref.a=8; // no issue
}
}
package b;
public class B extends A{
}
package c;
public class C extends B{
public void accessField(){
a = 2; //That works.
A ref = new A();
ref.a=8; // not visible!!
}
}
Any help much appreciated...
Thanks,
Sean.
Because C is in another package, and you're creating an A, not a subclass of A.
Flip the question on its head: why should it be visible? You already know the packaging rules, and you already know the field access rules.
In the last case you're making a new instance of an A object. This is completely different from using an instance of the subclass to access its parent class's members.
When you create a subclass, it creates a parent class first. The only subclass that has access to protected members in the parent instance is that subclass that the parent class was created with.