Let\'s assume I have classes A
, B
, and C
where class C
has readable and writable properties:
public class
Yes it is, but you have to go through some gyrations.
public interface Incrementable {
public void increment();
}
public interface Readable {
public int getScore();
}
public class C implements Incrementable, Readable
{
...
}
Now when you define the method in A that receives a reference to a B
instance, define that method to take an Incrementable
instead. For B
, define it to take a Readable
.
Not that you'd want to, but you could go up the stack trace (create an exception) and check the class that's calling your increment method.
Consider separating your class into separate interfaces so that each class only gets an object with the interface it needs. For example:
interface Incrementable { public void increment(); }
interface HasScore { public int getScore(); }
class C implements Incrementable, HasScore { /* ... */ }
class A {
public A(Incrementable incr) { /* ... */ }
}
class B {
public B(HasScore hs) { /* ... */ }
}
Of course, there are security implications but this should get you thinking in the right direction.
No it is not possible to do that.
Java has 4 scopes: private, protected, public and "package". Something that is public can be accessed from anywhere. protected only from subclasses. private is only that class. "package" scope is not named, but if you omit any of the other three, it is assumed package scope. This is only accessible by other classes in the same package.
HTH.
Although the straight answer is no, another workaround(an ugly one) could be to create two interfaces extending a third(or you could just take an Object as parameter): Reader and Writer, to pass the calling class as a parameter to each function:
public interface Caller;
public interface Reader extends Caller;
public interface Writer extends Caller;
public void increment(Caller c) {
if (c instanceof Writer) {
i++;
}
}