Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I limit the methods another class can call in Java?

Tags:

java

interface

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?

like image 574
sdasdadas Avatar asked Feb 05 '13 22:02

sdasdadas


People also ask

How can we prevent other classes from accessing a 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".

Can I call a method from another class Java?

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.

How do you stop a method from calling in Java?

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.


2 Answers

No, it is not possible to assign per-class access.

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.

like image 72
maerics Avatar answered Oct 29 '22 16:10

maerics


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.

like image 29
Jim Garrison Avatar answered Oct 29 '22 16:10

Jim Garrison