Let's assume I have classes A
, B
, and C
where class C
has readable and writable properties:
public class C {
private int i = 0;
// Writable.
public void increment() { i++; }
// Readable.
public int getScore() { return i; }
}
Is it possible to only let A
use the increment()
method and only let B
use the getScore()
method?
When you declare a method in a Java class, you can allow or disallow other classes and object to call that method. You do this through the use of access specifiers. The Java language supports five distinct access levels for methods: private, private protected, protected, public, and, if left unspecified, "friendly".
In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance.
JButton stopCaptureButton = new JButton("Stop"); panel. add(stopCaptureButton); stopCaptureButton. setBounds(875, 350, 80, 30); stopCaptureButton. addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ EspduReceiver.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With