0

I have below class with few public methods.

public class Sample{

  public void method1(){ }

  public void method2(){ }

  public void method3(){ }

  public void method4(){ }
}

I need to expose only first three methods to clients and not method4(). How can I create one more class exposing only the first 3 methods?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user755806
  • 6,565
  • 27
  • 106
  • 153

3 Answers3

2

create an interface which expose only 3 methods:

public interface ISample{
  public void method1();
  public void method2();
  public void method3();
}

Let the class implement it:

public class Sample implement ISample {
 // all method definitions are not changed
}

When you need full access, use type Sample, when restricted, then ISample:

Sample sample=new Sample();
sample.method4();
passToUser((ISample)sample);
Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38
  • I'm guessing `passToUser` takes `ISample` instances? If so, the cast is unnecessary. Note also that the `I` prefix is very common in .NET, but generally not used in Java. – Duncan Jones Jan 29 '14 at 10:58
  • This approach is also flawed, because the code receiving the `ISample` instance can cast it to `Sample` and access the hidden method. – Duncan Jones Jan 29 '14 at 11:07
  • @Duncan malicious client can read RestrictedSample.sample from your variant using reflection, Unsafe, or JNI. We don't know required defense level - maybe my variant is OK, maybe your variant is insecure. – Alexei Kaigorodov Jan 29 '14 at 11:21
  • That's a fair point. Perhaps I was too strong with my wording (r.e 'flawed'). However, I think it's worth noting that a simple cast overcomes this approach. – Duncan Jones Jan 29 '14 at 11:23
1

To make a public class that offers methods 1-3 only, wrap Sample in another class like this:

public class RestrictedSample {

  private Sample sample = new Sample();

  public void method1(){ sample.method1(); }

  public void method2(){ sample.method2(); }

  public void method3(){ sample.method3(); }
}

This is known as the façade pattern, or simply delegation.

Be warned: as long as Sample remains public, other code can construct instances of that class. That may not be a problem for you, but it's worth remembering.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
0

Better control over scope of visibility is one of the major things OSGi adds to Java. If this is a serious project, you may want to consider investing in learning OSGi.

If this is just something you're doing for yourself, or for class, you may want to consider something weaker but simpler such as marking the method deprecated or just renaming it to INTERNAL_USE_ONLY_method4.

Or leave the method as "package" access.

keshlam
  • 7,931
  • 2
  • 19
  • 33