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

前端 未结 6 907
猫巷女王i
猫巷女王i 2020-12-11 15:01

Let\'s assume I have classes A, B, and C where class C has readable and writable properties:

public class         


        
6条回答
  •  攒了一身酷
    2020-12-11 15:31

    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++;
         } 
    }
    

提交回复
热议问题